Why is lazy evaluation in Haskell "not being lazy"?

119 views Asked by At

When I tried the following code in cghi:

take 1 $ take 1 $ repeat [1..]

I was expecting the result of 1 instead of [[1,2,3,4,5,6,7,8,9,10,... printing on my terminal.

Why is lazy evaluation not functioning as I'm hoping under such situation?

2

There are 2 answers

0
Ry- On BEST ANSWER

take is of type Int -> [a] -> [a], i.e. it returns a list. It seems you’re looking for head, which returns one element.

head $ head $ repeat [1..]
0
bdonlan On

take 1 $ repeat [1..] returns [[1..]]. And then take 1 [[1..]] returns [[1..]], a no-op.