delegate from lambda expression
bearophile
bearophileHUGS at lycos.com
Sun Sep 9 16:55:28 PDT 2012
timotheecour:
> I'd like to achieve the following:
> ----
> import std.stdio,std.range,std.algorithm,std.array;
> void main(){
> auto dg=a=>a*2;
> auto a=iota(0,10);
> writeln(a.map!dg.array);
> }
> ----
> but this doesn't compile:
> Error: variable [...]dg type void is inferred from initializer
> delegate (__T26 a)
> {
> return a * 2;
> }
> , and variables cannot be of type void
>
> However this works:
> writeln(a.map!(a=>a*2).array);
Your code doesn't look good, I suggest to write less golfed D
code.
One solution to your problem is to define a function template
(note the static, that is currently needed, but maybe not in
future):
import std.stdio, std.range, std.algorithm, std.array;
void main() {
static dg(T)(T a) { return a * 2; }
auto items = iota(10);
items.map!dg().array().writeln();
}
> 1) why can't the compiler infer the type int(int) for dg?
Because in D there is no global inferencer, like a
Hindley–Milner (and you can't defer typing as in one recent
language).
I think not even Scala allows you to write code similar to:
auto dg = a => a * 2;
You need a language with global inferencing, like Haskell,
ShedSkin, Idris, etc.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list