[Haskell-beginners] Reversing a list
Jona Ekenberg
saikyun at gmail.com
Tue Jul 4 10:26:53 UTC 2017
Thank you both for your answers, I somehow thought ++ acted as both append
and concat, since I've mostly used it on strings where I haven't had to
think about it.
And thank you for the tips regarding adding explicit types and the reading
material. So far I feel that I'm able to follow along quite well, but it's
nice to have a second source!
Grateful regards,
Jona
Den 4 juli 2017 12:21 em skrev "Francesco Ariis" <fa-ml at ariis.it>:
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/
_______________________________________________
Beginners mailing list
Beginners at haskell.org
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20170704/bcb9d475/attachment-0001.html>
More information about the Beginners
mailing list