Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning Haskell: thunks returned by repeat

Tags:

haskell

I'm learning Haskell and wrote this function:

continueWith :: [a] -> a -> [a]
continueWith [] y     = repeat y
continueWith (x:xs) y = x : (continueWith xs y)

Now, I don't understand the behavior of GHCi:

GHCi> let x = continueWith [1, 2] 3
x :: [Integer]
GHCi> :sp x
x = _
GHCi> take 3 x
[1,2,3]
it :: [Integer]
GHCi> :sp x

The last sprint doesn't terminate, but I expected the thunk returned by repeat to be only evaluated up to the first cons:

...
GHCi> take 3 x
[1,2,3]
it :: [Integer]
GHCi> :sp x
x = 1 : 2 : 3 : _      <= This is not happening

What am I missing?

like image 966
Tilo Avatar asked Jun 18 '13 18:06

Tilo


1 Answers

The "problem" is that repeat y refers to itself,

repeat y = let ys = y:ys in ys

so once the first cons cell is evaluated, repeat y is completely evaluated. In ASCII art:

  (:) <-
 /  \  |
y    \_|

:sp prints as far as the thing is already evaluated ...

like image 74
Daniel Fischer Avatar answered Oct 17 '22 05:10

Daniel Fischer