简体   繁体   English

谓词在列表长度上的表现

[英]Performance of predicate on the length of a list

I have read (and also reasoned) that calculating the length of a list is not good for performance in Haskell. 我已经阅读(并且还推断)计算列表的长度对Haskell的性能不利。 However, i have long lists in my program and my requirement is to find that if length is greater than or less than some number X. 但是,我的程序中有很长的列表,我的要求是如果长度大于或小于某个数字X.

Is their already something in build in Haskell for these kind of predicates ? 对于这些谓词,他们已经在Haskell中构建了一些东西吗? or i have to resort to manual looping. 或者我不得不求助于手动循环。

On vanilla lists, you can check this using drop : 在vanilla列表中,您可以使用drop来检查:

cmpLen :: Int -> [a] -> Ordering
cmpLen n xs
    | n < 0     = GT
    | otherwise = case drop (n-1) xs of
        []  -> GT
        [_] -> EQ
        _   -> LT

However, this still takes as long as the value (not size, as is typical of asymptotic analysis!) of n . 然而,这仍然需要只要 (不是大小,是典型的渐进分析的!)的n If you intend to do this often, you can take a cue from Okasaki and build a new structure that caches the operation you want to be efficient. 如果您打算经常这样做,您可以从Okasaki获取一个提示并构建一个新的结构来缓存您想要高效的操作。 I have wanted this a few times before, and found the following sort of interface convenient in those cases: 之前我曾经想过这几次,并且在这些情况下发现以下类型的界面很方便:

type LenList a = (Sum Word, [a])
singleton x = (1, [x])
cons x = (singleton x<>)
length = getSum . fst
elems  = snd

Note that, since LenList a is already a Monoid , you get some of the usual operations for free, eg there is an empty LenList a named mempty , and concatenation is given by (<>) . 请注意,由于LenList a已经是Monoid ,因此您可以免费获得一些常用操作,例如,有LenList a名为mempty的空mempty ,并且(<>)给出了连接。 Some operations (notably the ones that produce infinite lists) will not be implementable for this type. 某些操作(特别是产生无限列表的操作)将无法实现此类型。 However, you pay an O(1) price on each construction operation to make asking for the length of one of these O(1), which can be a nice tradeoff in many situations. 但是,您需要为每个施工操作支付O(1)价格,以询问其中一个O(1)的长度,这在许多情况下可能是一个很好的权衡。

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

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