我正在学习Haskell并编写了此函数:

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

现在,我不了解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

最后一个sprint不会终止,但是我希望 repeat 返回的thunk只能在第一个缺点之前进行评估:
...
GHCi> take 3 x
[1,2,3]
it :: [Integer]
GHCi> :sp x
x = 1 : 2 : 3 : _      <= This is not happening

我想念什么?

最佳答案

“问题”是repeat y指向自身,

repeat y = let ys = y:ys in ys

因此,一旦第一个cons单元被评估,repeat y将被完全评估。在ASCII艺术中:
  (:) <-
 /  \  |
y    \_|
:sp可以打印出已经评估过的东西。

07-24 18:30
查看更多