2011-09-06 77 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。

我希望有帮助。