我正在学习Haskell并编写了这个函数:
continueWith :: [a] -> a -> [a]
continueWith [] y = repeat y
continueWith (x:xs) y = x : (continueWith xs y)
Run Code Online (Sandbox Code Playgroud)
现在,我不明白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
Run Code Online (Sandbox Code Playgroud)
最后一个sprint没有终止,但我预计返回的thunk repeat只能评估到第一个缺点:
...
GHCi> take 3 x
[1,2,3]
it :: [Integer]
GHCi> :sp x
x = 1 : 2 : 3 : _ <= This is not happening
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
"问题"是repeat y指自身,
repeat y = let ys = y:ys in ys
Run Code Online (Sandbox Code Playgroud)
因此,一旦评估了第一个cons细胞,就会对其进行repeat y全面评估.在ASCII艺术中:
(:) <-
/ \ |
y \_|
Run Code Online (Sandbox Code Playgroud)
:sp 就已经评估的东西打印...