[Haskell-beginners] Reversing a list
Frerich Raabe
raabe at froglogic.com
Tue Jul 4 10:36:28 UTC 2017
On 2017-07-04 12:06, Jona Ekenberg wrote:
> Hello,
>
> I'm currently going through the exercises in chapter 3 of Real World
> Haskell. One of the exercises challenges me to create a function which
> takes a list and makes a palindrome of it.
>
> I tried to solve it this way:
>
> palindrome :: [t] -> [t]
> palindrome xs = xs ++ (reverse xs)
> where
> reverse [] = []
> reverse (x:xs) = (reverse xs) ++ x
>
> But when I try to compile this I get this error:
[..]
This is caused by Haskell trying hard to make your code type check but the
noticing that it just cannot make the parts fit together.
I suspect the cause of this is the definition
reverse (x:xs) = (reverse xs) ++ x
What's noteworthy about this is:
1. The type of the ':' constructor you used in the pattern match is 'a ->
[a] -> [a]', i.e. the first argument is of some type 'a' (in Haskell
nomenclature, 'x :: a') and the second argument is a list (i.e. 'xs :: [a]').
So your compiler knows that no matter what type 'x' is, 'xs' will be a list
of those things.
2. The type of the '++' function you used on the right-hand side is '[a] ->
[a] -> [a]', i.e. the first and the second argument must be of the same type
(a list of things). Since the second argument must be a list, this means that
'x' must be a list and hence (considering 1. above) 'xs' must be a list of
lists.
This means that your 'reverse' definition must be of type '[[a]] -> [a]': it
takes a list of list of things and yields a list of things. I.e. it takes and
returns different type sof things.
This however is in conflict with your first definition:
palindrome xs = xs ⧺ (reverse xs)
For 'xs ⧺ (reverse xs)' to be sound (to 'type-check'), the expressions 'xs'
and '(reverse xs)' have to be of the same type. And since 'xs' is also an
argument to 'reverse' it means that 'reverse' has to take and yield values of
the same type.
You can resolve this conflict by changing
reverse (x:xs) = (reverse xs) ++ x
to
reverse (x:xs) = (reverse xs) ++ [x]
--
Frerich Raabe - raabe at froglogic.com
www.froglogic.com - Multi-Platform GUI Testing
More information about the Beginners
mailing list