Tuesday, December 3, 2013

Take a Function as a parameter in D

D is an improvement over C++. However, because of the lack of documentation, you need to be studious to use these improvements. One of the features that D introduces is an alias parameter, which we can use to make higher-order functions. If you're familiar with function pointers, these can be used as well, however, there is an alternative in D called delegates.

Without further adieu, here is an implementation of map, a function that takes another function and applies it to an array.

T[] map(alias func, T)(T[] data}{
if(data.length == 1) return func(data[0]);
else return [func(data[0])] ~ map!(func,T)(data[1..$]);

The noteworthy chunk of this code is "(alias func, T)". This is a declaration to "capture" an alias and some type when the function is called, and to take and return a dynamic array of type T, whatever type it is. The generic is important in this instance, since dynamic arrays are a container for any type.

Calling higher-order functions in D
To call this function, one would use "map!(name_of_function,type)(list)". Where name_of_function is either the name of a function or a function literal, and type is any type, user-defined or not. An example, done completely with literals:

Calling with literals
map!(((y) {return 10-y;}),int)([1,2,3,4,5,6,7,8,9]) // Returns [9,8,7,6,5,4,3,2,1]

Here, the syntax ((y) {return 10-y;}) is a function literal, called a lambda is some languages.

higher-order functions in D
D higher-order functions
D lambdas
lambda D

No comments:

Post a Comment