【发布时间】:2020-08-07 01:55:52
【问题描述】:
如果无法理解为什么我在 repl.it 上运行下面的代码时它不会停止。
-- The second argument is meant to be an infinite ascending list, don't bother yourself with any other case
isin :: Int -> [Int] -> (Bool, [Int])
isin n [] = (False, []) -- This case is unnecessary because the list is infinite, but just for completion
isin n l@(x:xs) =
case n `compare` x of
LT -> (False, l)
EQ -> (True, xs)
GT -> isin n xs
>>> isin 2 [1..]
-- prints nothing --Edit
-- expected (True, [3,4,5... --Edit
在我看来,这个的执行应该是这样的:
-- underscore is meant to be "unevaluated". (Probably not 100% accurate but you can follow my idea)
isin 2 1:_ -- first call
2 `compare` 1 -- GT
isin 2 _
isin 2 2:_ -- second call
2 `compare` 2 -- EQ
(True, _)
(True, 3:_) -- returned result
AFAIK,这应该可以正常工作,除非元组是严格的,在这种情况下我将使用不同的结构......但我 90% 确定它们不是
如果您想知道,这个想法是 isin 将在同一个列表中被多次调用,并且数字越来越多,所以我可以在检查时低头。
【问题讨论】:
-
无法复制。当我运行它时,我得到
(True,[3,4,5,6,7... -
等等。您是否将“无限长输出”与“永远运行”混为一谈?它们不是一回事。
-
元组并不严格,但打印是。当您将表达式输入 ghci 时,您是在要求 ghci 打印它。为了打印一对,ghci 必须首先打印左侧组件(简单且短),然后打印右侧组件(也简单,但很长......)。尝试仅打印左侧组件,或仅打印右侧组件的前 10 个元素,以查看是否返回 ghci 提示符。
-
如果您调用
fst (isin 2 [1..]),它将终止。问题是元组的第二个值是一个无限列表,所以它不能完全打印第二部分。它将永远运行。 -
@JosephSible-ReinstateMonica 实际上我正在使用在线回复:repl.it/languages/haskell 以便向同事展示。所以我不知道它的配置
标签: haskell recursion pattern-matching repl.it