2011-09-06 76 views
5
isPalindrome::(Eq a) => [a] -> Bool 
isPalindrome [] = True 
isPalindrome [x] = True 
isPalindrome (x1:xs:x2:[]) 
    | x1 == x2 = isPalindrome xs 
    |otherwise = False 


[1 of 1] Compiling Main    (myHas.hs, interpreted) 

myHas.hs:37:27: 
    Couldn't match expected type `[a]' against inferred type `a1' 
     `a1' is a rigid type variable bound by 
      the type signature for `isPalindrome' at myHas.hs:33:18 
    In the first argument of `isPalindrome', namely `xs' 
    In the expression: isPalindrome xs 
    In the definition of `isPalindrome': 
     isPalindrome (x1 : xs : x2 : []) 
         | x1 == x2 = isPalindrome xs 
         | otherwise = False 

我是一個初學者的haskell程序員,並沒有得知我爲什麼得到這個錯誤,請任何幫助嗎?初學者哈斯克爾程序員

+0

現在這個問題解決了嗎? – MGwynne

回答

13

你把xs看成是一個列表,但(x1:xs:x2:[])認爲它是你的輸入列表的一個元素。

注意(x1:xs:x2:[])僅匹配列表和3層的元件,並且x1xsx2a類型的元素。

所以xsa型的,但是當你將它傳遞給isPalindrome,我們只能假設它必須是東西的清單,這樣類型的系統調用類型[a1]

編碼你想要的最簡單的方法是:

isPalindrome::(Eq a) => [a] -> Bool 
isPalindrome l = l == (reverse l) 
7

下面是一個簡單易懂的答案,類似於您嘗試:

isPalindrome [] = True 
isPalindrome [x] = True 
isPalindrome xs = (head xs == last xs) && isPalindrome (init (tail xs)) 

所以空或一個元素的列表一個迴文和一個更長的列表是一個迴文,如果第一個和最後一個元素相等,「中間」元素也是迴文。

請注意,MGwynne的回答是更高性能,因爲上面的解決方案必須在每一步遍歷列表。

+0

+1用於給出類似於問題的答案,然後解釋爲什麼不使用它! – MGwynne

5

我覺得這裏需要對用於列表的語法的解釋,目前還沒有給出。首先,在Haskell列表類型的定義是:

data [a] = a : [a] | [] 

這表示,名單是空的([]),或者從(:)構造函數,它有它的左側參數的a提出,和另一個列表(定義中的[a])。這意味着列表[1,2,3]實際上是1 : (2 : (3 : [])),但是這也可以寫爲1 : 2 : 3 : []

當模式相匹配的列表中,你的匹配上這些構造函數:

f [] = … -- match the empty list 

f (x:[]) = … -- match a list with one element, which you name x 

f (x:xs) = … -- match the first element of the list, and whatever the rest of 
      -- the list is, but it must have at least one element. if you call 
      -- f [1,2,3], x will be bound to 1, and xs will be bound to [2,3] 
      -- because [1,2,3] is the same as (1:[2,3]) 

f (x:y:xs) = … -- matches a list with at least two elements, which you 
       -- call x and y respectively 

f (xs:ys:zs:things) = … -- matches a list with at least three elements, 
         -- which you name, xs, ys and zs. 
從這個

所以,我希望這是現在很清楚,

f (x1:xs:x2:[]) 

列表匹配具有正好三個要素,你的名字是x1,xs和x2。

我希望有幫助。