简体   繁体   English

foldl'和foldr'的默认定义似乎很奇怪

[英]Default definitions of foldl' and foldr' seem weird

Default definitions of foldl' and foldr' seem weird. foldl'foldr'默认定义似乎很奇怪。 They have default definition as: 它们的默认定义为:

class Foldable t where
    -- ...
    foldr' f z0 xs = foldl f' id xs z0
      where f' k x z = k $! f x z
    -- ...
    foldl' f z0 xs = foldr f' id xs z0
      where f' x k z = k $! f z x
    -- ...

Why not?: 为什么不?:

class Foldable t where
    -- ...
    foldr' f = foldr (\x z -> f x $! z)
    -- ...
    foldl' f = foldl (\z x -> flip f x $! z)
    -- ...

Generally speaking, foldl' is best for things that look kind of like cons-lists and foldr' is best for things that look kind of like snoc-lists. 一般而言, foldl'最适合看起来像缺点列表的东西,而foldr'最适合看起来像snoc列表的东西。 The situations are symmetrical, so let's just look at cons-lists, where foldl' had better be good. 情况是对称的,所以让我们看一下“缺点”列表,其中“ foldl'最好是好的。

You've probably read that foldl for cons-lists can lead to space leaks if it's not optimized well enough. 您可能已经读过,如果对cons-lists的foldl的优化不够好,可能会导致空间泄漏。 Well, that's exactly what will happen here. 好吧,这就是这里会发生的事情。 f' is strict, but none of its results are demanded until the fold has reached the end of the list! f'是严格的,但是直到弃牌数到达列表末尾时才要求其结果!

The default definitions give a little twist, which makes even naive compilation (or interpretation) work properly. 默认的定义有点扭曲,即使是天真的编译(或解释)也能正常工作。

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

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