【问题标题】:Haskell circular definition interruptHaskell 循环定义中断
【发布时间】:2018-02-19 08:14:42
【问题描述】:

大家好,我遇到了一件奇怪的事情,试图在 Haskell 中学习循环定义。我们有这两种情况:

module Main
where    
  mgood = 1:head (tail (tail mgood)):mgood

  list = take 10 mgood

  main = do

       print list

对于上面的代码,我得到了这个输出 [1,1,1,1,1,1,1,1,1,1] 我明白为什么但问题出在这段代码中:

module Main
where
  mbad = 1:head (tail (tail (tail mbad))):mbad

  list = take 10 mbad

  main = do

       print list

我在哪里得到这个输出 [1, {Interrupted!}。谁能解释一下为什么会发生这种情况以及这两种情况有什么区别?

【问题讨论】:

  • 请不要破坏问题 - 即使您碰巧发布了这些问题。

标签: haskell functional-programming


【解决方案1】:

您的两个定义都符合result = foo : bar : result 模式。所以我们最终得到的,在这两种情况下,都是一个看起来像这样的循环列表:

foo : bar : foo : bar : foo : bar : ...

在这两种情况下foo1,所以它不依赖于其他任何东西。但是bar 可以。

mgood 中,您将bar 定义为等于列表的第三个元素,因此bar 等于foo,即1。所以foobar 都是1,这就是你得到的:1s 的无限列表。

mbad 中,您将bar 定义为等于第四个 元素。所以bar 等于它自己。在尝试评估 bar 时,bar 的这种无限递归定义会导致无限循环。

【讨论】:

    猜你喜欢
    • 2013-05-14
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多