While working through Real World Haskell, I tried to complete the palindrome exercise using the following code solution:
palin :: [a] -> [a]
palin list = list ++ rev list
where rev list
| null list = []
| otherwise = rev (tail list) ++ (head list)
Which raised a “cannot construct an infinite type error. However, simply replacing the parenthesis around the head list with square brackets, and it works correctly, as demonstrated in the following example:
palin :: [a] -> [a]
palin list = list ++ rev list
where rev list
| null list = []
| otherwise = rev (tail list) ++ [head list]
I don’t really understand why it matters, nor do I understand what does the “cannot construct infinite type a = [a]” error means. Could someone explain this?
In the last line, you are trying to append a non-list to a list.
head listgives the first item of the list, which is typea. When you try to use++to append, you can’t append something that isn’t a list to a list. By appending[head list], you are appending a list of 1 item to the other list. The[]construct the single item list in this case.