Array comprehensions and the like

downs default_357-line at yahoo.de
Fri Jul 18 23:46:11 PDT 2008


For what it's worth, here's the tools versions:

bearophile wrote:
> I have already discussed about this topic a couple of times in the past, but this time I have more things to talk about :-)
> 
> I think Python-like array comprehensions and the like are quite useful, their light syntax replaces the need for map, filter, xfilter, xmap, some usages of flatten, xflatten, and some more things, while being quite readable still and short.
> 
> Recently a DMDScript too has gained array comprehensions:
> http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7#Array_comprehensions
> 
> 
> Few examples in Python 3:
> 
> # eager list (array) comp, 1D:
> a = [x * x for x in lazyit if x > 5]
auto a = lazyit /select/ ex!("x -> x > 5") /map/ ex!("x -> x*x");
> 
> # eager list comp, 2D:
> parts = [[part.strip() for part in line.split()] for line in file("txt")]
> 
auto parts = (cast(string) "txt".read()).split("\n") /map/ (string s) { return s.split(" ").strip(); };

> # set comprehension
> squares = {x*x for x in xrange(100)}
> 
auto squares = Range[100] /map/ ex!("x -> x*x");

> # dict comprehension
> multi = {c:c*i for i,c in enumerate("abcd")}
> 
Can't do that yet. Sad.
> # lazy, 1D
>>>> mat = [[0, 3, 0, 3], [9, 8, 1, 4], [6, 7, 6, 6]]
>>>> flat = (abs(el) for row in mat for el in row if el % 2)
>>>> flat

T[] iterToField(T)(void delegate(void delegate(T)) dg) {
  T[] res; dg((T t) { res ~= t; });
  return res;
}

auto mat = [[0, 3, 0, 3], [9, 8, 1, 4], [6, 7, 6, 6]];
auto flat = (void delegate(ref int) dg) {
  foreach (ref row; mat) foreach (ref el; row) if (el % 2) dg(el);
};

> <generator object at 0x00A8E1E8>
>>>> list(flat)
> [3, 3, 9, 1, 7]
> 
writefln(iterToField(flat));

 --downs



More information about the Digitalmars-d mailing list