logoalt Hacker News

s-zeng • today at 12:56 PM • 3 replies • view on HN

A neat fact about foldr on lists, unlike foldl, is that it actually passes control flow entirely to the accumulating function on each fold step. That means you can use foldr to implement arbitrary traversals of lists, including foldl' or list traversals that exit early. See https://github.com/quchen/articles/blob/master/useful_techni...


Replies

Twey • today at 10:30 PM

In other words, `foldr` (flipped about) takes a list to its Church encoding: since it just ‘replaces the constructors’ (`:` becomes `f`, `[]` becomes `z`), it doesn't lose any information from the list: if you can write a function by recursing on a list then you can write it using `foldr`.

tome • today at 5:11 PM

Yes, because foldr is equivalent to for_, that is, iterating over a container and performing an effectful action (what in other languages would be called "doing something") for each element. Uses of foldr can always be rewritten to uses of for_, and I find things much clearer in terms of for_!

(This is explained in my article "foldl traverses with State, foldr traverses with anything": https://h2.jaguarpaw.co.uk/posts/foldl-traverses-state-foldr...)

➕ show 1 reply
someonebaggy • today at 3:02 PM

At some point doesn't it become easier to write the function explicitly? As in

    go [] = ...
    go head:remainder = ...
instead of hacking it together with a fold?
➕ show 4 replies