Higher-order functions?

Jacob Carlborg doob at me.com
Wed Apr 11 02:17:11 PDT 2012


On 2012-04-11 10:45, Xan wrote:
> Good answer.
>
> For the other hand, what is the simplest method for implementing this
> (in pseucode) in D:
>
> Sure:
>
> FUNC someprocedure(int a, int b, func<int, int: int> f) int
> RETURN f(a, b)
> }
>
> And call it with:
>
> IO.writeLine("add: " .. someprocedure(2, 3, { a, b => a + b }))
> IO.writeLine("multiply: " .. someprocedure(2, 3, { a, b => a * b }))
>
> (Read the => as "gives")
>
> Is it possible to have this?
>

If I understand the above code correctly:

import std.stdio;

int someprocedure (int a, int b, int delegate (int, int) f)
{
     return f(a, b);
}

void main ()
{
     writeln("add: ", someprocedure(2, 3, (a, b) => a + b));
     writeln("multiply: ", someprocedure(2, 3, (a, b) => a * b));
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list