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.

===tags(ignore)===
higher-order functions in D
D higher-order functions
D lambdas
lambda D

3 comments:

  1. To take full benefit of all Hotmail features, you need to understand them and configure your account setting. Please dial 0800-029-4639 and make things easier for you. Here you can talk to our Hotmail executives and get proper assistance about Hotmail issues.
    Hotmail Helpline Number UK

    ReplyDelete
  2. Gmail might trouble you with some unknown issues that can’t be resolved by your own. You can fix such technical problems by just contacting the technical team available at Gmail Helpline Number UK for instant answers. The service professionals are experienced and well proficient for the same.

    ReplyDelete
  3. Hotmail account not opening problem make you feel disturbed at several point of time. If you don’t know what will be the ideal step to fix this problem, you can take assistance of Hotmail Customer Care Number UK. They have the best professional knowledge to undo your doubts within no time.
    Hotmail Phone Number UK
    Hotmail Support Number UK
    Hotmail Contact Number UK

    ReplyDelete