A look at a modern programming language and how it can enhance the productivity and workflow of developers while promising higher execution performance. We will be talking about metaprogramming, functional programming and type systems in a pragmatic way mixed with some examples from `vibe.d` web framework.
By Yazan Dabain - Senior System Engineer, Arabia Weather
2. WHAT IS D?
A statically typed, compiled language with C-like syntax.
A languages that provides productivity and modelling power at the same time as
high performance and efficiency.
“D demonstrates that it is possible to build a powerful programming language that is both easy to use and generates fast code.”
4. WALTER BRIGHT
Creator of the D programming language.
Developer of multiple C and C++ compilers:
Zorland C, Zortech C++, Digital Mars C++, ...
Aware of the problems in the existing languages,
he decided to write his own language.
And so, D started out in 1999.
5. ANDREI ALEXANDRESCU
Co-designer of the D programming language.
Joined in 2006.
Renowned author/co-author of:
Modern C++ Design: Generic Programming
and Design Patterns Applied [2001]
C++ Coding Standards: 101 Rules, Guidelines,
and Best Practices [2004]
The D Programming Language [2009]
6. TIMELINE OF PROGRAMMING LANGUAGES
1970 1975 1980 1985 1990 1995 2000 2005 2010 2015
D2.068.1
C C++
Objective-C
Perl
Erlang
Bash
Haskell
Python
Visual Basic
Lua
PHP
Java
JavaScript
Ruby
D1
Python 2
C#
Scala D2
Python 3
Go
C++11
Java 7
C++14
Swift
Java 8
7. QUICK LOOK AT DSYNTAX
import std.stdio;
void main()
{
writeln("Hello JOSA!");
}
/**
* Returns the sum of elements.
*
* Params:
* elements = array of integers to sum
*/
int sum(int[] elements)
{
int sum = 0;
foreach (element; elements)
sum += element;
return sum;
}
/**
* Writes each argument and its length
* to stdout.
*/
void main(string[] args)
{
import std.stdio;
foreach (arg; args[1 .. $])
writefln("%s: %s", arg, arg.length);
}
» ./main Welcome to JOSA TechTalks
Welcome: 7
to: 2
JOSA: 4
TechTalks: 9
8. QUICK LOOK AT DSYNTAX - BASIC TYPES,
ARRAYS AND ASSOCIATIVE ARRAYS
// logical data type:
bool
// integral data types:
byte, short, int, long, cent
ubyte, ushort, uint, ulong, ucent
// floating data types:
float, double, real
// character data types
char, wchar, dchar
// defining arrays:
int[] nums = [1, 2, 3, 4];
// accessing arrays:
int sum = nums[0] + nums[$ 1];
// slicing arrays:
int[] slice = nums[0 .. $ / 2];
// defining an associative array:
int[string] wordCount;
// setting a value:
wordCount["hello"] = 1;
// check if key exists:
bool exists = "hello" in wordCount;
// reading a value:
int count = wordCount["hello"];
// reading a value with a default:
int count = wordCount.get("hello", 0);
9. QUICK LOOK AT DSYNTAX - TYPE INFERENCE
// without type inference
int num = 0;
string str = "D rocks!";
DateTime time = DateTime(2015, 9, 16);
// with automatic type inference
auto num = 0;
auto str = "D rocks!";
auto time = DateTime(2015, 9, 16);
10. QUICK LOOK AT DSYNTAX - LAMBDAS
// function declaration
int square(int x)
{
return x * x;
}
// in lambda form
auto summation = (int x, int y) => x + y;
auto multiplication = (int x, int y) => x * y;
auto subtraction = (int x, int y) => x y;
// usage like a normal function
auto result = summation(5, 10);
11. QUICK LOOK AT DSYNTAX - UNIFORM FUNCTION
CALL SYNTAX
auto withLastName(string firstName, string lastName) {
return firstName ~ " " ~ lastName;
}
// can be used as:
auto fullName = "Yazan".withLastName("Dabain");
import std.datetime;
auto duration = 5.days + 12.hours;
// vs
auto duration = days(5) + hours(12);
12. QUICK LOOK AT DSYNTAX
// Example:
// find all words which are 4 letters or more
// ps. no need to be picky about punctuation
import std.algorithm;
auto quote = "I would love to change the world, "
"but they won't give me the source code.";
// without UFCS
auto result = filter!(word => word.length >= 4)(splitter(quote));
// with UFCS
auto result = quote.splitter().filter!(word => word.length >= 4)();
16. CODE DUPLICATION AND VERBOSITY
int add(int a, int b)
{
return a + b;
}
float add(float a, float b)
{
return a + b;
}
// what we want is something similar to:
Type add(Type a, Type b)
{
return a + b;
}
28. COMPILE TIME FUNCTION EVALUATION (CTFE)
“Compile-time function evaluation is the ability of a compiler, that would
normally compile a function to machine code and execute it at run time, to
execute the function at compile time.”
29. COMPILE TIME FUNCTION EVALUATION (CTFE)
auto fromRoman(string roman) {
auto flat = roman
.replace("IV", "IIII")
.replace("IX", "VIIII")
.replace("XL", "XXXX")
.replace("XC", "LXXXX");
auto value =
flat.count('I')
+ flat.count('V') * 5
+ flat.count('X') * 10
+ flat.count('L') * 50
+ flat.count('C') * 100;
return value;
}
struct Roman {
enum opDispatch(string name)
= fromRoman(name);
}
void main()
{
writeln(Roman.XV);
writeln(Roman.IIX);
writeln(Roman.VXCII);
}
0000000000432708 <_Dmain>:
push %rbp
mov %rsp,%rbp
mov $0xf,%edi
callq 4334a0 <std.stdio.writeln>
mov $0xa,%edi
callq 4334a0 <std.stdio.writeln>
mov $0x61,%edi
callq 4334a0 <std.stdio.writeln>
xor %eax,%eax
pop %rbp
retq
xchg %ax,%ax
30. REFLECTION
“Reflection is the ability of a computer program to examine and modify its own
structure and behavior (specifically the values, meta-data, properties and
functions).”
31. COMPILE-TIME REFLECTION IN D
struct Person {
int id;
string username;
DateTime birthdate;
}
// we can use the compiler to tell us
// what members Person struct contain
[__traits(allMembers, Person)].writeln();
// prints ["id", "username", "birthdate"]
// or if Person has some specific member
if (__traits(hasMember, Person, "fname"))
writeln("Yes, Person has a firstname");
void create(string title, float price) {
…
}
// we can also retrieve function parameter
// names, default values, ...
assert(
[ParameterIdentifierTuple!create] ==
["title", "price"]
);
32. COMPILE-TIME REFLECTION AND CODE
GENERATION
auto smaller(T)(T a, T b) {
foreach (member; __traits(allMembers, T)) {
if (__traits(getMember, a, member) < __traits(getMember, b, member))
return true;
else if (__traits(getMember, a, member) > __traits(getMember, b, member))
return false;
}
return false; // equal
}
struct Person {
string username;
DateTime birthdate;
}
auto one = Person("joe", DateTime(1990, 1, 1));
auto two = Person("john", DateTime(1980, 1, 1));
writeln(smaller(one, two));
33. POWERFUL COMBINATION OF FEATURES
import pegged.grammar;
/// Numbers
mixin(grammar(`
Number:
Scientific <~ Floating ( ('e' / 'E' ) Integer )?
Floating <~ Integer ('.' Unsigned )?
Unsigned <~ [09]+
Integer <~ Sign? Unsigned
Hexa <~ [09afAF]+
Sign < '' / '+'
`));
auto tree = Number("25.12e+21");
// use the parse tree
34. POWERFUL COMBINATION OF FEATURES
import vibe.data.json;
struct Foo {
int number;
string str;
}
auto f = Foo(12, "hello");
string json = serializeToJsonString(f);
assert(json == `{"number":12,"str":"hello"}`);
f = deserializeJson!Foo(`{"number": 42, "str": "the answer"}`);
assert(f.number == 42);
assert(f.str == "the answer");
39. REST INTERFACE - SERVER
class WeatherProvider : WeatherAPI {
private string m_location;
Weather getWeather() { return Weather("sunny", 25); }
@property void location(string location) { m_location = location; }
@property string location() { return m_location; }
}
shared static this() {
auto router = new URLRouter();
router.registerRestInterface(new WeatherProvider());
auto settings = new HTTPServerSettings;
settings.port = 8080;
listenHTTP(settings, router);
}
40. REST INTERFACE - REMOTE CLIENT
auto client = new RestInterfaceClient!WeatherAPI("http://127.0.0.1:8080/");
auto weather = client.getWeather();
logInfo("Weather: %s, %s °C", weather.status, weather.temperature);
client.location = "Paris";
logInfo("Location: %s", client.location);
41. REST INTERFACE - JS CLIENT
shared static this() {
auto restSettings = new RestInterfaceSettings();
restSettings.baseURL = URL("http://127.0.0.1:8080/");
auto router = new URLRouter();
router.registerRestInterface(new WeatherProvider(), restSettings);
router.get("/weather.js", serveRestJSClient!WeatherAPI(restSettings));
auto settings = new HTTPServerSettings;
settings.port = 8080;
listenHTTP(settings, router);
}
<! in javascript >
<script src="weather.js"></script>
var weather = WeatherAPI.getWeather();
console.log(weather.status);
console.log(weather.temperature);
42. LINKS AND RESOURCES
D Programming Language dlang.org
D forums forum.dlang.org
Programming in D - Ali Çehreli ddili.org/ders/d.en/
TDPL - Andrei Alexanderscu
D Templates - Philippe Sigaud github.com/PhilippeSigaud/D-templates-tutorial
Rosetta Code (various tasks solved in D) rosettacode.org/wiki/Category:D
IRC channel #d on freenode.org
Dub package manager code.dlang.org