Cool listcomp

Check this post, which demonstrates the power of Haskell's list comprehensions:

f :: Int -> [ (Int, Int, Int) ]

f n = [ (x, y, z) |
x <- [ 1 .. n ],
y <- [ x+1 .. n ],
z <- [ y+1 .. n ],
(x * x) + (y * y) == (z * z) ]

I first thought there was some special magic going on, like maybe some Prolog-like matching, but then I realized that you can do the same in Python:

def f(n):
return [(x,y,z)
for x in range(1, n+1)
for y in range(x+1, n+1)
for z in range(y+1, n+1)
if x*x + y*y == z*z]
print f(20)

(Which isn't so surprising after all, as Python "borrowed" list comprehensions from Haskell... but still.)

Leave a Comment