I am trying to implement a recursive function for Tower of Hanoi.
The algorithm is:
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")]
This is my implementation
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")
However I got an error said there is un-exhausted pattern
.
What does it mean an how can I solve it?
Arguments to Haskell functions are actually patterns that the supplied values are matched against.
a
is an irrefutable pattern that always succeeds by matching up the variable a
with the supplied value, whether "a"
, "b"
, "c"
or something else entirely.
"a"
is also a pattern, but it will only succeed when matched up with a matching value, "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
So, do not enclose your arguments in quotes when defining functions, if you want them to be interpreted as variable patterns.