2017-02-26 29 views
1

我正在嘗試實施河內塔的遞歸函數。哈希克爾實施河內塔時出錯

的算法是:

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。 這是什麼意思我該如何解決它?

+1

參數不需要用引號引起來。在這裏,他們甚至不應該。 –

回答

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 

所以,定義函數時不附上論據報價,如果你希望他們被解釋爲可變模式。

+0

非常感謝。這真的很有幫助。 – RunningPig