[英]Haskell - foldl' in terms of foldr and performance issues
While studying fold
in depth with A tutorial on the universality and expressiveness of fold I found an amazing definition of foldl
using foldr
: 在使用
fold
的普遍性和表现力的教程深入研究fold
,我发现了使用foldr
的foldl
的惊人定义:
-- I used one lambda function inside another only to improve reading
foldl :: (b -> a -> b) -> b -> [a] -> b
foldl f z xs = foldr (\x g -> (\a -> g (f a x))) id xs z
After understanding what is going on, I thought I could even use foldr
to define foldl'
, which would be like this: 在了解了正在发生的事情之后,我想我甚至可以使用
foldr
来定义foldl'
,这将是这样的:
foldl' :: (b -> a -> b) -> b -> [a] -> b
foldl' f z xs = foldr (\x g -> (\a -> let z' = a `f` x in z' `seq` g z')) id xs z
Which is parallel to this: 这与此平行:
foldl' :: (b -> a -> b) -> b -> [a] -> b
foldl' f z (x:xs) = let z' = z `f` x
in seq z' $ foldl' f z' xs
foldl' _ z _ = z
It seems that both of them are running in constant space (not creating thunks) in simple cases like this: 在这样的简单情况下,它们似乎都在恒定的空间(不创建thunk)中运行:
*Main> foldl' (+) 0 [1..1000000]
500000500000
May I consider both definitions of foldl'
equivalent in terms of performance? 我可以考虑
foldl'
在性能方面的两种定义吗?
In GHC 7.10+, foldl
and foldl'
are both defined in terms of foldr
. 在GHC 7.10+中,
foldl
和foldl'
都是根据foldr
定义的。 The reason that they weren't before is that GHC didn't optimize the foldr
definition well enough to participate in foldr/build
fusion. 他们之前没有的原因是GHC没有足够好地优化
foldr
定义以参与foldr/build
fusion。 But GHC 7.10 introduced a new optimization specifically to allow foldr/build
fusion to succeed while using foldl'
or foldl'
defined that way. 但GHC 7.10引入了一种新的优化,特别是允许
foldr/build
融合成功,同时使用这种方式定义的foldl'
或foldl'
。
The big win here is that an expression like foldl' (+) 0 [1..10]
can be optimized down to never allocating a (:)
constructor at all. 这里的最大胜利是像
foldl' (+) 0 [1..10]
这样的表达式可以优化到永远不会分配一个(:)
构造函数。 And we all know that the absolute fastest garbage collection is when there's no garbage to collect. 我们都知道,绝对最快的垃圾收集是在没有垃圾收集的时候。
See http://www.joachim-breitner.de/publications/CallArity-TFP.pdf for information on the new optimization in GHC 7.10, and why it was necessary. 有关GHC 7.10中新优化的信息,以及为什么有必要,请参见http://www.joachim-breitner.de/publications/CallArity-TFP.pdf 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.