问题描述
inserts 1 [2,3] = [[1,2,3],[2,1,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,3]*** Exception: <interactive>:2:1-53: Non-exhaustive patterns in function inserts
有谁知道缺失的模式是什么?
解决方法
当我按照您的代码定义 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]]