【问题标题】:Missing pattern in inserts function插入功能中缺少模式
【发布时间】:2021-02-01 11:55:53
【问题描述】:

我有这个功能inserts where

inserts 1 [2,3] = [[1,2,3],[2,1,3],[2,3,1]]

这是定义(直接来自 Bird 和 Gibbons 的 Haskell 算法设计)

inserts :: a -> [a] -> [[a]]
inserts x [] = [[x]]
inserts x (y:ys) = (x:y:ys) : map (y:) (inserts x ys)

我已经用上面的例子在 ghci 中尝试过了,但是我得到了以下异常

[[1,2,3],[2,1,3]*** Exception: <interactive>:2:1-53: Non-exhaustive patterns in function inserts

有谁知道缺失的模式是什么?

【问题讨论】:

  • inserts n = zipWith (\xs ys -> xs (n:ys)) inits tails
  • inserts n xs = [ a ++ n:b | (a,b) &lt;- zip (inits xs) (tails xs) ]
  • 另外,this answer 与主题有关(不是错误)。 (免责声明,这是我写的)。

标签: haskell ghci non-exhaustive-patterns multiline-repl-definition


【解决方案1】:

当我根据你的代码定义inserts然后运行inserts 1 [2,3]时,我没有收到任何错误,并且返回了正确的结果。但是,当我这样做时,我可以复制错误:

Prelude> inserts x [] = [[x]]
Prelude> inserts x (y:ys) = (x:y:ys) : map (y:) (inserts x ys)
Prelude>
Prelude> inserts 1 [2,3]
[[1,2,3],[2,1,3]*** Exception: <interactive>:2:1-53: Non-exhaustive patterns in function inserts

所以问题不在于你的职能。相反,您将其错误地输入到 GHCi 中。当你像这样在 GHCi 中输入一个多行函数时,它会定义 两个 函数而不是一个:首先它定义了inserts x [] = [[x]],然后它用inserts x (y:ys) = (x:y:ys) : map (y:) (inserts x ys) 覆盖了这个定义。在 GHCi 中输入多行函数的正确方法是用 :{ :} 包围定义:

Prelude> :{
Prelude| inserts :: a -> [a] -> [[a]]
Prelude| inserts x [] = [[x]]
Prelude| inserts x (y:ys) = (x:y:ys) : map (y:) (inserts x ys)
Prelude| :}
Prelude> inserts 1 [2,3]
[[1,2,3],[2,1,3],[2,3,1]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多