[Haskell-beginners] Reversing a list
Francesco Ariis
fa-ml at ariis.it
Tue Jul 4 10:20:36 UTC 2017
On Tue, Jul 04, 2017 at 12:06:39PM +0200, 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
Hello Jona,
let's analyse the error.
It points to this bit:
palindrome xs = xs ++ (reverse xs)
And it says: I expected [[t]], but you gave me [t]. Whenever I encounter
such an error I try to write explicit type signatures so to make diagnosing
easier. In your example
palindrome :: [t] -> [t]
palindrome xs = xs ++ (reverse xs)
where
reverse :: [t] -> [t] -- explicit type signature
reverse [] = []
reverse (x:xs) = (reverse xs) ++ x
If we :reload ghci complains again, the offending bit being
reverse (x:xs) = (reverse xs) ++ x
^
Expected type is [t1] but we passed t. Not it is clear! The type of `++` is:
λ> :t (++)
(++) :: [a] -> [a] -> [a]
and `x` is a single element. When we replace `x` with `[x]` everything works.
Does that help?
-F
P.S.: Real World Haskell is an excellent book but sometimes can be a tad
difficult to follow. If you want to integrate with another source, CIS194 [1]
is an excellent choice: free, thorough, full of home-works and interactive.
[1] http://www.cis.upenn.edu/~cis194/fall16/
More information about the Beginners
mailing list