Beginner haskell programmer

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

I am a novice haskell programmer and have no idea why I get this error, any help please?

+5
source share
3 answers

You treat it xslike a list, but (x1:xs:x2:[])it assumes that it is an element of your input list.

Note that it (x1:xs:x2:[])will only correspond to lists with 3 elements, and x1, xsand x2will be type elements a.

So, it xshas a type a, but as you pass it in isPalindrome, we can only assume that it should be a list of something, so the type system calls the type [a1].

The easiest way to encode:

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

, :

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

, , - , , "" .

, MGwynne much , .

+7

, , , . -, 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.

, .

+5
source

All Articles