[英]Haskell list length alternative
Hi I've got a list on Haskell with close to 10^15 Int's in it and I'm trying print the length of the list. 嗨,我在Haskell上有一个列表,其中包含接近10 ^ 15的整数,我正在尝试打印列表的长度。
let list1 = [1..1000000000000000] -- this is just a dummy list I dont
print list1 length -- know the actual number of elements
printing this takes a very long time to do, is there another way to get the number of elements in the list and print that number? 打印此文件需要花费很长时间,是否还有另一种方法来获取列表中的元素数量并打印该数量?
I've occasionally gotten some value out of lists that carry their length. 从偶尔列出的清单中我有时会得到一些价值。 The poor man's version goes like this: 可怜的人的版本是这样的:
import Data.Monoid
type ListLength a = (Sum Integer, [a])
singletonLL :: a -> ListLength a
singletonLL x = (1, [x])
lengthLL :: ListLength a -> Integer
lengthLL (Sum len, _) = len
The Monoid
instance that comes for free gives you empty lists, concatenation, and a fromList
-alike. 免费提供的Monoid
实例为您提供空列表,串联和fromList
相似。 Other standard Prelude
functions that operate on lists like map
, take
, drop
aren't too hard to mimic, though you'll need to skip the ones like cycle
and repeat
that produce infinite lists, and filter
and the like are a bit expensive. 在列表map
运行的其他标准Prelude
函数(例如map
, take
, drop
并不是很难模仿,尽管您将需要跳过诸如cycle
并repeat
生成无限列表的那些函数,而filter
等则有点昂贵。 For your question, you would also want analogs of the Enum
methods; 对于您的问题,您还需要类似Enum
方法的方法。 eg perhaps something like: 例如,也许像:
enumFromToLL :: Integral a => a -> a -> ListLength a
enumFromToLL lo hi = (fromIntegral hi-fromIntegral lo+1, [lo..hi])
Then, in ghci, your example is instant: 然后,在ghci中,您的示例是即时的:
> lengthLL (enumFromToLL 1 1000000000000000)
1000000000000000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.