Ruby-style "each" in D?
bearophile
bearophileHUGS at lycos.com
Wed Mar 19 08:48:11 PDT 2014
Andrei Alexandrescu:
> Pros and cons are already being discussed. Destroy!
>
> https://github.com/D-Programming-Language/phobos/pull/2024
I proposed the same function in D.learn, but this discussion
needs a list of use cases and usage examples, otherwise you can't
decide in vacuum.
It's named "foreach" in Scala:
http://twitter.github.io/scala_school/collections.html#foreach
Elsewhere I suggested a function that could be named tap() that's
usable to debug UFCS chains, interspersing it in the chain, to
add imperative calls to writeln. You can replace a each() with a
tap + some kind of eager consumer.
In many cases what I want to put in each() is a writef/writefln,
you can do it like this (binaryReverseArgs is in std.functional):
foo
.bar
.spam
.binaryReverseArgs!writefln("%(%s-%): %d", 5);
With a shorter flipping name it gets better:
foo
.bar
.spam
.flipTwoArgs!writefln("%(%s-%): %d", 5);
or even (http://zvon.org/other/haskell/Outputprelude/flip_f.html
) (flips only the first two args and doesn't flip the successive
ones):
foo
.bar
.spam
.flip!writefln("%(%s-%): %d", 5);
Let's say in each() you want to do something different, like
incrementing a variable:
foo
.bar
.spam
.each!(n => x += n);
Is this good enough?
If you want to double the contents of an array:
myArray.each((ref x) => x * 2);
But in D you can also use:
myArray[] *= 2;
I guess you can't use each() on opApply-based iterables, while
you can with foreach(). This makes each() less useful.
Is the following code supported? And what is each() receiving
from the associative array?
int[string] aa;
aa.each(...);
Perhaps you must use:
int[string] aa;
aa.byKey.each(...);
aa.byValue.each(...);
aa.byPair.each(...);
While arrays should be OK, but there is no index support:
int[] arr;
arr.each(...);
If you need dynamic array index support:
int[] arr;
arr.enumerate.each(...);
Is this supported?
int[10] arr2;
arr2.each(...);
Or do you have to use this?
int[10] arr2;
arr2[].each(...);
Bye,
bearophile
More information about the Digitalmars-d
mailing list