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?
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With