Reputation: 21
I am stuck with the following question:
Write a function mangle :: String -> String
which removes the first letter of a word and attaches it at the end.
What I have so far:
mangle :: [a] -> [a] -> [a] (I suspect that this is possibly wrong)
mangle x
= a ++ b
where
a = tail x
b = head x
Can anyone help me and tell/explain what I should put on the top?
Thanks!
Upvotes: 1
Views: 79
Reputation: 476624
There are two problems here. First of all, the signature of mangle
should be mangle :: [a] -> [a]
. Indeed, it takes as parameter a [a]
, a list of a
s, and it returns a list of a
s.
Another problem is that head :: [a] -> a
returns a single element. So you can not use (++) :: [a] -> [a] -> [a]
since that expects two lists with the same type of items.
You thus need to wrap the head x
in a singleton list:
mangle :: [a] -> [a]
mangle x = tail x ++ [head x]
There is still another problem: head
and tail
can not work with empty lists. You thus probably should write a base-case for an empty list as well.
We can make the function more elegant by performing pattern matching instead of using head
and tail
, like:
mangle :: [a] -> [a]
mangle [] = …
mangle (x:xs) = xs ++ [x]
Upvotes: 2