Haskell 实施汉诺塔时出错
Haskell error when implementing Tower of Hanoi
我正在尝试为汉诺塔实现递归函数。
算法是:
Move n−1 disks from peg AA to peg C using peg B as intermediate storage.
Move the nth disk from peg A to peg B,
Move n−1 disks from peg C to peg BB using peg A as intermediate storage.
示例:
hanoi 2 "a" "b" "c" =
[("a","c"), ("a","b"), ("c","b")]
这是我的实现
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi x "a" "b" "c"
| x <= 0 = []
| x == 1 = [("a", "b")]
| otherwise = (hanoi (x-1) "a" "c" "b") ++ [("a", "b")] ++ (hanoi (x-1) "c" "b" "a")
但是我收到一条错误消息 there is un-exhausted pattern
。
这是什么意思,我该如何解决?
Haskell 函数的参数实际上是提供的值所匹配的模式。
a
是一个无可辩驳的模式,无论是 "a"
、"b"
、"c"
,它总是通过将变量 a
与提供的值匹配来成功或者完全是其他东西。
"a"
也是一种模式,但它 只有 在与 匹配的 值匹配时才会成功,"a"
:
~> let f "a" = 1
f :: Num a => [Char] -> a
~> f "a"
1
it :: Num a => a
~> f "c"
*** Exception: <interactive>:3:5-13: Non-exhaustive patterns in function f
因此,如果您希望将参数解释为变量模式,则在定义函数时不要将参数括在引号中。
我正在尝试为汉诺塔实现递归函数。
算法是:
Move n−1 disks from peg AA to peg C using peg B as intermediate storage.
Move the nth disk from peg A to peg B,
Move n−1 disks from peg C to peg BB using peg A as intermediate storage.
示例:
hanoi 2 "a" "b" "c" =
[("a","c"), ("a","b"), ("c","b")]
这是我的实现
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi x "a" "b" "c"
| x <= 0 = []
| x == 1 = [("a", "b")]
| otherwise = (hanoi (x-1) "a" "c" "b") ++ [("a", "b")] ++ (hanoi (x-1) "c" "b" "a")
但是我收到一条错误消息 there is un-exhausted pattern
。
这是什么意思,我该如何解决?
Haskell 函数的参数实际上是提供的值所匹配的模式。
a
是一个无可辩驳的模式,无论是 "a"
、"b"
、"c"
,它总是通过将变量 a
与提供的值匹配来成功或者完全是其他东西。
"a"
也是一种模式,但它 只有 在与 匹配的 值匹配时才会成功,"a"
:
~> let f "a" = 1
f :: Num a => [Char] -> a
~> f "a"
1
it :: Num a => a
~> f "c"
*** Exception: <interactive>:3:5-13: Non-exhaustive patterns in function f
因此,如果您希望将参数解释为变量模式,则在定义函数时不要将参数括在引号中。