www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Lambda are capricious little animals indeed

reply "Derix" <derix dexample.com> writes:
So, I wanted to wrap my head a little tighter around those 
strange animals that are lamdas.

I wrote the simpliest program utilizing a lambda :

import std.stdio;
void main(){
	writeln({return "foobar";});
}

and it yields 43106C, which does not look like "foobar" at all, 
but rather, I suspect, like a pointer or something.
So I tried
        writeln(typeid({return "foobar";}));
which in turn yelds immutable(char)[]()*
that hints further to a pointer.
I get the immutable(char)[] : an immutable array of characters, 
why not. But I really don"t get the set of parens between the 
square brackets and the asterisk. Could that mean that what I get 
is in fact a pointer to a function ? (said function having no 
arguments, or having void as sole argument or ...)

Now, the question (and the very point of a lambda if I get it 
right) would be to get this function to evaluate (and precisely 
return the string "foobar" in this example).

What syntactic subtility am I missing ?
Oct 27 2013
next sibling parent reply "Maurice" <m-ou.se m-ou.se> writes:
On Sunday, 27 October 2013 at 14:01:31 UTC, Derix wrote:
 So, I wanted to wrap my head a little tighter around those 
 strange animals that are lamdas.

 I wrote the simpliest program utilizing a lambda :

 import std.stdio;
 void main(){
 	writeln({return "foobar";});
 }
You still have to call the lambda just like a function, with (): import std.stdio; void main() { writeln({return "foobar";}()); }
Oct 27 2013
parent "Maurice" <m-ou.se m-ou.se> writes:
On Sunday, 27 October 2013 at 14:10:50 UTC, Maurice wrote:
 On Sunday, 27 October 2013 at 14:01:31 UTC, Derix wrote:
 So, I wanted to wrap my head a little tighter around those 
 strange animals that are lamdas.

 I wrote the simpliest program utilizing a lambda :

 import std.stdio;
 void main(){
 	writeln({return "foobar";});
 }
You still have to call the lambda just like a function, with (): import std.stdio; void main() { writeln({return "foobar";}()); }
Some clarification: import std.stdio; void main() { auto f = {return "foobar";}; // f behaves like a function. auto s = f(); // it can be called like any other function, it takes no parameters. writeln(s); }
Oct 27 2013
prev sibling parent "David Nadlinger" <code klickverbot.at> writes:
On Sunday, 27 October 2013 at 14:01:31 UTC, Derix wrote:
 I get the immutable(char)[] : an immutable array of characters, 
 why not. But I really don"t get the set of parens between the 
 square brackets and the asterisk. Could that mean that what I 
 get is in fact a pointer to a function ? (said function having 
 no arguments, or having void as sole argument or ...)
Yes, this is correct. You still have to call the lambda: { return 42; }(). David
Oct 27 2013