haskell can not construct infinite type

坚强是说给别人听的谎言 提交于 2021-02-11 04:26:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!