简体   繁体   English

haskell无法构造无限类型

[英]haskell can not construct infinite type

I'm new to haskell. 我是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. reverse' (tail list)的类型为[a] ,而首部head list的类型为a ,因此编译器会尝试使其变为a ~ [a] ,这显然是行不通的。 Instead, you can use the ++ operator and put head list into a list itself: 相反,你可以使用++运算符,并把head list到列表本身:

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. 但是请记住,这不是一个非常有效的解决方案,因为Hassell列表是单链接列表,所以连接到Haskell列表的末尾比较慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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