简体   繁体   English

为无限列表 Haskell 定义一个函数

[英]Define a function for an infinite list Haskell

Im trying to write the function longer :: [a] -> Int -> Bool Which decides if the provided list is longer than the parameter.我试图将函数写得longer :: [a] -> Int -> Bool这决定了提供的列表是否比参数长。 So far I wrote:到目前为止,我写道:

longer :: [a] -> Int -> Bool
hossz (x:xs) = length (x:xs)
hossz [] = 0
longer [] _ = False
longer (x:xs) y | y<0 = error ("negative parameter")
                    | hossz(x:xs)>y = True
                    | otherwise = False

This all works fine and dandy until I provide it with an infinite list (longer [1..] 10 for example), where it will get stuck in an infinite loop of some sort and just doesn't finish running.在我为它提供一个无限列表(例如更长的 [1..] 10)之前,这一切都很好,很花哨,它会卡在某种无限循环中,只是没有完成运行。 So the question is, is there maybe a way I could define it, where if it gets an infinite list it just returns True and doesn't try to calculate the whole thing?所以问题是,是否有一种方法可以定义它,如果它得到一个无限列表,它只会返回 True 而不会尝试计算整个事情? Thank you in advance先感谢您

length is trying to compute the length of the list, which takes forever for an infinite list. length正在尝试计算列表的长度,对于无限列表,这需要永远。

You don't need to compute the length at all, though.不过,您根本不需要计算长度。 You only need to recurse on the tail with a smaller integer.您只需要使用较小的整数在尾部递归。 When the the integer hits 0, the list is either empty or not;当整数达到 0 时,列表要么为空,要么不为空; it doesn't matter how long it is.多久都没有关系。

longer :: [a] -> Int -> Bool
longer _ n | n < 0 = True
longer xs 0 = ...
longer [] n = False  -- n > 0
longer (x:xs) n = longer xs (n - 1)

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

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