Re: fuction Return function

2014-07-26 Thread Meta via Digitalmars-d-learn

On Saturday, 26 July 2014 at 20:49:30 UTC, seany wrote:
Can a function return a function in D? Sorry if i missed the 
answer somewhere


Yup, you can return functions, delegates, or function pointers.

int function(int) returnsFunc1()
{
return function(int n) { return n; };
}

int function(int) returnsFunc2()
{
//Even works for nested functions.
//Make them static so they don't
//create a context pointer to
//returnsFunc2's frame
static int fun(int n)
{
return n;
}

return &fun;
}

int test(int n)
{
return n;
}

int function(int) returnsFunc3()
{
return &test;
}

int delegate(int) makeAdder(int numToAdd)
{
return delegate(int n) { return n + numToAdd; };
}

void main()
{
auto func1 = returnsFunc1();
assert(func1(1) == 1);

auto func2 = returnsFunc2();
assert(func2(2) == 2);

auto func3 = returnsFunc3();
assert(func3(3) == 3);

auto add3 = makeAdder(3);
assert(add3(1) == 4);
}


Re: fuction Return function

2014-07-26 Thread sigod via Digitalmars-d-learn

On Saturday, 26 July 2014 at 20:49:30 UTC, seany wrote:
Can a function return a function in D? Sorry if i missed the 
answer somewhere


Just alias your function signature:

```d
alias MyFunctionType = void function(int);
```

Example from my own code:
```d
alias DeserializeBody = TLObject function(InBuffer);

DeserializeBody[uint] registerAll(modules...)()
{
// ...
}
```



fuction Return function

2014-07-26 Thread seany via Digitalmars-d-learn
Can a function return a function in D? Sorry if i missed the 
answer somewhere