Higher-order functions?

Xan xancorreu at gmail.com
Wed Apr 11 02:51:12 PDT 2012


On Wednesday, 11 April 2012 at 09:43:27 UTC, Timon Gehr wrote:
> On 04/11/2012 11:37 AM, Xan wrote:
>> On Wednesday, 11 April 2012 at 09:17:12 UTC, Jacob Carlborg 
>> wrote:
>>> 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);
>>> }
>>>
>>
>>
>> Yes, you undertood correcty.
>>
>> Your code gives me an error:
>>
>> $ gdmd-4.6 funcions.d
>> funcions.d:10: expression expected, not '>'
>> funcions.d:10: found 'a' when expecting ','
>> funcions.d:11: expression expected, not '>'
>> funcions.d:11: found 'a' when expecting ','
>>
>>> void main ()
>>> {
>>>    writeln("add: ", someprocedure(2, 3, (a, b) => a + b));
>>>    writeln("multiply: ", someprocedure(2, 3, (a, b) => a * 
>>> b));
>>> }
>>
>>
>
> AFAIK GDC does not yet support the new lambda literal syntax.
>
> You can use
>
> void main ()
> {
>     writeln("add: ", someprocedure(2, 3, (a, b) { return a + b; 
> }));
>     writeln("multiply: ", someprocedure(2, 3, (a, b) { return a 
> * b; }));
> }

Better but with error ;-)

$ gdmd-4.6 func2.d
func2.d:10: Error: undefined identifier a
func2.d:10: Error: undefined identifier b
func2.d:10: Error: function func2.someprocedure (int a, int b, 
int delegate(int, int) f) is not callable using argument types 
(int,int,_error_ delegate(_error_, _error_))
func2.d:10: Error: cannot implicitly convert expression 
(__dgliteral1) of type _error_ delegate(_error_, _error_) to int 
delegate(int, int)


With:

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) { return a + b; } 
  ));
     writeln("multiply: ", someprocedure(2, 3, (a, b) { return a * 
b; } ));
}


What is the error?



More information about the Digitalmars-d-learn mailing list