Ruby-style "each" in D?

Jakob Ovrum jakobovrum at gmail.com
Fri Mar 21 09:25:46 PDT 2014


On Friday, 21 March 2014 at 12:29:31 UTC, bearophile wrote:
> So before taking any decision on the matter, more experiments 
> and usage examples are necessary, where you have longer chains. 
> If you have a longer chain:
>
> items
> .sort()
> .group
> .map!(g => g[1] / double(s.length))
> .map!(p => -p * p.log2)
> .sum
> .each(...);
>
> using a each() allows you to keep a nice column. If you use 
> foreach your formatting and your logic has a hiccup, because 
> you are mixing two different styles:
>
> foreach (item; items
>                .sort()
>                .group
>                .map!(g => g[1] / double(s.length))
>                .map!(p => -p * p.log2)
>                .sum) {
>     // Do something imperative here.
> }
>
> But this is not a real example (it computes the entropy of 
> items, and you usually don't need an each there), so more usage 
> examples are needed. Taking a look at real world usages of 
> foreach() in Scala could be useful.

The former example doesn't become functional just because you 
managed to use UFCS, it's just imperative code deceptively 
disguised as functional code. The clear separation in the latter 
example is a *good thing*.



More information about the Digitalmars-d mailing list