Array comprehensions and the like

bearophile bearophileHUGS at lycos.com
Sat Jul 19 02:45:32 PDT 2008


downs:

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

If you show here how to use your tools people may learn (how) to use them a bit more.


> > # 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(); };

Sorry, that Python version of mine is "wrong", because the split splits according to the white space, so a successive stripping is useless, so a more meaningful code may be:
parts = [[part.strip() for part in line.split(",")] for line in file("txt")]

The Python version scans the lines lazily, so it works on mega files too. Your version is eager according to the lines, I presume. In my code I have used xfile() that's lazy.
But even if you change your code like this and ignore the lazy thing:

> auto parts = (cast(string) "txt".read()).split("\n") /map/ (string s) { return s.split(",").strip(); };

I think it does something different, because you may need two /map/ to emulate the two for of the Python version.


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

That Python version creates a set, while isn't your squares an array?


> > # 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));

I don't see the abs(), but that's not much important.

Bye,
bearophile



More information about the Digitalmars-d mailing list