The D programming language is a statically typed, natively compiled language that has some significant features inspired by Python.
Arrays and associative arrays are built into the language. There are no list comprehensions, but the std.range and std.algorithm libraries fill much of that void. For example, here's a way to sum up all the even numbers from 0 to 100 in D:
auto result = reduce!"a + b"(
filter!"a % 2 == 0"(
iota(0, 100)
)
);
There are no keyword arguments so far, but closures are there. Tuples are supported, but not unpacked automatically.
In D, you avoid specifying classes (and types in general) everywhere with the auto
keyword and with templates. For example, here is generic code to find the product of array of any numeric type:
// The return type of product() is inferred.
auto product(T)(T[] array) {
T ret = 1;
foreach(num; array) { // typeof(num) is inferred.
ret *= num;
}
return ret;
}
D's metaprogramming support consists of compile time introspection (for example, you can iterate over the fields of a class or struct at compile time), runtime type information, and templates that are actually designed for metaprogramming beyond simple generics. For example, here's how to write a generic function that generates a default comparison operation for two structs, which is useful if you need an arbitrary total ordering for something like a binary tree:
/**Returns -1 if lhs < rhs, 0 if lhs == rhs, 1 if lhs > rhs.*/
int compareStructs(T)(T lhs, T rhs) {
foreach(tupleIndex, value; lhs.tupleof) {
if(value < rhs.tupeof[tupleIndex]) {
return -1;
} else if(value > rhs.tupleof[tupleIndex]) {
return 1;
}
}
return 0;
}