简体   繁体   中英

haskell can not construct infinite type

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) 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM