[Haskell-beginners] Lazy evaluation and list comprehensions

Felipe Almeida Lessa felipe.lessa at gmail.com
Wed Aug 8 23:14:18 CEST 2012


Just use GHCi's :print command =).

Prelude> let xs = [1..42] :: [Int]; x = 17; ys = [ y | y <- xs, y >= x ]
Prelude> :print xs
xs = (_t1::[Int])
Prelude> :print ys
ys = (_t2::[Int])

Initially nothing is evaluated (as expected).

Let's try forcing ys to WHNF:

Prelude> ys `seq` ()  -- forcing to WHNF
()
Prelude> :print xs
xs = 1 : 2 : 3 : 4 : 5 : 6 : 7 : 8 : 9 : 10 : 11 : 12 : 13 : 14 :
     15 : 16 : 17 : (_t3::[Int])
Prelude> :print ys
ys = 17 : (_t4::[Int])

So xs had to be forced until the first element of ys appeared (since
WHNF decides between [] and _:_).  We didn't explicitly evaluate ys's
first element but as it needed to be evaluated before it already
appears evaluated now.

Same thing if you continue forcing ys:

Prelude> tail ys `seq` ()  -- forcing tail to WHNF
()
Prelude> :print xs
xs = 1 : 2 : 3 : 4 : 5 : 6 : 7 : 8 : 9 : 10 : 11 : 12 : 13 : 14 :
     15 : 16 : 17 : 18 : (_t5::[Int])
Prelude> :print ys
ys = 17 : 18 : (_t6::[Int])

Cheers,

-- 
Felipe.



More information about the Beginners mailing list