我正在尝试为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.
Eample:
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
。
我怎么解决它是什么意思?
答案 0 :(得分:1)
Haskell函数的参数实际上是提供的值与之匹配的模式。
a
是一种无可辩驳的模式,通过将变量a
与提供的值("a"
,"b"
,"c"
或其他内容相匹配,始终可以成功完全是。
"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
因此,如果您希望将它们解释为变量模式,请不要在定义函数时将参数括在引号中。