Jav*_*rgz 1 haskell ghci non-exhaustive-patterns multiline-repl-definition
我有这个功能inserts,其中
inserts 1 [2,3] = [[1,2,3],[2,1,3],[2,3,1]]
Run Code Online (Sandbox Code Playgroud)
这是定义(直接来自Bird和Gibbons的Haskell算法设计)
inserts :: a -> [a] -> [[a]]
inserts x [] = [[x]]
inserts x (y:ys) = (x:y:ys) : map (y:) (inserts x ys)
Run Code Online (Sandbox Code Playgroud)
我已经用上面的例子在 ghci 中尝试过,但我得到以下异常
[[1,2,3],[2,1,3]*** Exception: <interactive>:2:1-53: Non-exhaustive patterns in function inserts
Run Code Online (Sandbox Code Playgroud)
有谁知道缺少的模式是什么?
当我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
Run Code Online (Sandbox Code Playgroud)
所以问题不是你的功能。相反,您错误地将其输入到 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]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |