简体   繁体   English

Haskell:无法构造无限类型

[英]Haskell: cannot construct the infinite type

I got a list of tuples (day:month) and want to find the month with the biggest amount of days. 我有一个元组列表(天:月),想查找天数最多的月份。

I made a function that accepts my list of tuples and list of months (or just 1) to check and returns the maximum amount of dates in one month in specified period 我做了一个函数,它接受我的元组列表和月份列表(或仅1个)以检查并返回指定时期内一个月中的最大日期数

maxweekends x [] = 0
maxweekends x [n] = length (filter ((==n).snd) x)
maxweekends x (y:ys) = max (maxweekends x [y]) (maxweekends x ys)

Then I wrote some simple function to use it, but I cant compile it because of "cannot construct the infinite type" error. 然后,我编写了一些简单的函数来使用它,但是由于“无法构造无限类型”错误而无法对其进行编译。 I already spent a few hours with this error but I just cant understand what is wrong. 我已经花了几个小时解决这个错误,但我只是不明白哪里出了问题。

func x [] = 0
func x (y:ys)
    | maxweekends x y < maxweekends x ys = func x ys
    | otherwise =  y

In theory it should call itself until there is no month with bigger amount of dates and then just return answer. 从理论上讲,它应该自我调用,直到没有月份有更大的日期,然后才返回答案。

Thanks. 谢谢。

Edit: here is traceback of error 编辑: 这是错误的回溯

Your infinite type arises from the fact that you call maxweekends with xy and x ys . 您无限类型的产生是因为您用xyx ys调用maxweekends Since the type of maxweekends :: Eq b => [(a, b)] -> [b] -> Int specifies that given the "second" parameter is of type [b] , then the first parameter is a type of [(a, b)] , this means that x should be [(a, b)] (for the first call) and [(a, [b])] (for the second call) at the same time, which is impossible. 由于maxweekends :: Eq b => [(a, b)] -> [b] -> Int指定给定“ second”参数的类型为[b] ,因此第一个参数的类型为[(a, b)] ,这意味着x应该同时为[(a, b)] (对于第一次调用)和[(a, [b])] (对于第二次调用),这是不可能的。

I think it might be better to first restructure this. 我认为最好首先进行重组 Let us first construct a function that looks like: 让我们首先构造一个看起来像这样的函数:

groupLength :: Eq b => Int -> b -> [(a, b)] -> Int
groupLength d _ [] = d
groupLength _ x ys = length (filter ((x==) . snd) ys)

This will thus for a given "month" x obtain the number of elements in the list with as second item of the tuple that "month". 这将从而对于给定的“月” x获得列表中的元素的数量与为“月”的元组的第二项。

Now we can generate an "argmax" that calculates for which x , fx produces a maximum value: 现在我们可以生成一个“ argmax”,用于计算xfx产生最大值的值:

argmax :: Ord b => (a -> b) -> [a] -> Maybe (a, b)
argmax _ [] = Nothing
argmax f (x:xs) = Just (go x (f x) xs)
    where go x y [] = (x, y)
          go x y (x2:xs) | y <= y2 = go x y xs
                         | otherwise = go x2 y2 xs
              where y2 = f x2

So now it is only a matter of combining the the groupLength (which is an abstract version of your maxweekends with argmax (which is more or less what your func is after). I leave this as an exercise. 因此,现在只需要结合groupLength (这是maxweekendsargmax的抽象版本)(这或多或少是您的func所需要的)。

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

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