List comprehensions

Albert Hofkamp hat at se-46.wpa.wtb.tue.nl
Tue Dec 21 12:21:27 EST 1999


On Tue, 21 Dec 1999 03:44:24 GMT, Alexander Williams
      <thantos at chancel.org> wrote:

>>      print [ (x,y) | x <- xs, x>3, y <- xs, y>x ]
>
>Oooh, Haskell syntax.  I'm feeling perfectly at home.  :)

Then you are going to like our specification language chi :-)
Say for yourself:

 *[ x<0 -> x:=x+2 
  | x>0 -> x:=x-3
  ]

is much nicer than

 while x<0 or x>0:
   if x<0:
     x:=x+2
   elif x>0:
     x:=x-3

<big smile>



>>I'd like to have that, except that I don't know how to write that
>>down. On the other hand, in our field, it is probably not needed much.
>
>I'm not sure that writing parallel iterators as a single line is
>really condusive to understanding what is going on under the hood.
>You can always nest iterators, as well ...  That's always fun.  :)

But that is not the same thing. For example,

  xs:=[1,2]; y:=[3,4]

then nested, you get
  [ (1,3), (1,4), (2,3), (2,4) ]

and parallel, you get
  [ (1,3), (2,4) ]

In a different posting, I say a few things about parallel iterations.


>>Also, I'd like to get rid of fold().
>
>Hey, I /like/ fold (foldl, foldr)!  After all, the results of fold
>aren't lists, they're single values.  It makes sense for it to be a

Oops, I should have been clearer. I'd like to have fold functionality
inside the kind of expressions we are discussing.

>    sumGreaterThanFive(lst) = foldl(operator.plus,
>                                    [e <- lst, e>5])

In our language, you cannot write an expression just like that. You'd
have to define a full function for it.
I saw the explanation of this in the Python tutorial(?) with the map and
filter functions.
I think that many users never use it, because it is too much hassle to
have to write a separate function. They rather write a for-loop instead.
(note that map and filter are not very powerful in that respect. They
replace just a single loop. One has to nest calls explicitly before you
get power like

  [ x+3 | y <- ys, z <- zs, y>z, x <- xs, y+z<x ]

and define separate functions for each level.
(anyone care to do this with map and filter ?)

That is basically what makes this list comprehension construct so attractive.

I'd like to have the same kind of flexibility for fold as well (much of
the above holds equally well for fold). It gets even more interesting if
you can freely mix both concepts (with the limitation that fold delivers
a single value).
On the other hand, it is quite a different beast, so mixing may be a bad
idea. Your idea of making it look like a function is nice, I have to
consider that a bit while I walk home.


Albert
---
Look ma, windows without Windows !!



More information about the Python-list mailing list