[Tutor] Nested list comprehensions

Kent Johnson kent37 at tds.net
Mon May 15 02:16:23 CEST 2006


John Fouhy wrote:
> On 15/05/06, w chun <wescpy at gmail.com> wrote:
>> anyone know if list comps work the same way in haskell?
> 
> Slightly not what you asked, but you can do some funky things with
> list comprehensions in Haskell.
> 
> Check this out:
> 
> fibs = 0 : 1 : [ a + b | (a, b) <- zip fibs (tail fibs)]
> 
> The python translation would be something like:
> 
> fibs = [0, 1] + [ a+b for (a, b) in zip(fibs, fibs[1:])]
> 
> But you can't quite do that in python :-)

You can come pretty close with generators, though it hurts to think 
about what is actually going on behind the scenes here:

In [1]: import itertools

In [2]: def fibs():
    ...:     yield 0
    ...:     yield 1
    ...:     fib1 = fibs()
    ...:     fib2 = fibs()
    ...:     fib2.next()
    ...:     for a, b in itertools.izip(fib1, fib2):
    ...:         yield a+b
    ...:
    ...:

In [3]: f=fibs()

In [4]: [f.next() for i in range(10)]
Out[4]: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Kent



More information about the Tutor mailing list