June 03, 2014 Re: for, foreach identifier allowed in c throws error in d | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steven Schveighoffer | On Tuesday, 3 June 2014 at 13:23:36 UTC, Steven Schveighoffer wrote: > On Mon, 02 Jun 2014 17:25:24 -0400, John Colvin <john.loughran.colvin@gmail.com> wrote: > >> On Monday, 2 June 2014 at 20:23:12 UTC, Steven Schveighoffer wrote: >>> On Mon, 02 Jun 2014 15:58:01 -0400, Steven Schveighoffer <schveiguy@yahoo.com> wrote: >>> >>> >>>> I'm trying to think of a way to do this without loops, but not sure. >>> >>> I'm surprised, I looked for some kind of "apply" function like map, but just calls some function with each element in the range. >>> >>> Something like this would make this a 1 (2?) liner: >>> >>> if(i == t.length) writeln(t) else each!((x) => {t[i] = x; foo(i+1);})(iota(x.length)); >>> >>> But I can't find a phobos primitive for each. Would have expected it in std.algorithm or std.functional? >>> >>> -Steve >> >> Its been discussed a few times. There were some objections (IIRC Walter thought that there was no significant advantage over plain foreach). > > Indeed, foreach is like such a construct: > > ... else each!((x) {t[i] = x; foo(i+1);})(iota(t.length)); > ... else foreach(x; 0 .. t.length) {t[i] = x; foo(i+1);} > > It's even shorter and clearer. > > I agree with Walter. Since such a construct by definition wouldn't return anything, you can't chain it. There really is little reason to have it. > > -Steve It's more useful like this: import std.algorithm, std.stdio, std.range; template call(Funcs ...) { auto call(T)(T val) { foreach(F; Funcs) { F(val); } return val; } } void doubleIt(ref int i) { i *= 2; } void evalAll(R)(R r) { foreach(v; r){} } void main() { [1,2,3,4].map!(call!(doubleIt, write))().evalAll(); //prints 2468 assert([1,2,3,4].map!(call!doubleIt)().equal([2,4,6,8])); } Eager iteration and mapping functions that don't return anything useful are orthogonal. |
Copyright © 1999-2021 by the D Language Foundation