问题
I'm new to haskell. I wrote a simple code. But it does not work. I'm getting this 'can not construct infinite type' error. How does it fix.
reverse' list
| null list = []
| otherwise = (reverse' (tail list)) : (head list)
回答1:
The problem arises from your use of the :
operator, which has the type
(:) :: a -> [a] -> [a]
So it takes an element and a list, and returns a new list with that element prepended on. Where you have
reverse' (tail list) : head list
-- parentheses removed since they're not needed
the type of reverse' (tail list)
is [a]
, and the type of head list
is a
, so the compiler tries to make it so that a ~ [a]
, which obviously can't work. Instead, you can use the ++
operator and put head list
into a list itself:
reverse' (tail list) ++ [head list]
But keep in mind that this is not a very efficient solution, concatenation onto the end of Haskell lists is slow since they're singly linked lists.
来源:https://stackoverflow.com/questions/23772866/haskell-can-not-construct-infinite-type