gpt4 book ai didi

haskell - 学习 Haskell : thunks returned by repeat

转载 作者:行者123 更新时间:2023-12-04 19:09:10 25 4
gpt4 key购买 nike

我正在学习 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打印到已经评估过的东西......

关于haskell - 学习 Haskell : thunks returned by repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17175996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com