logoalt Hacker News

japgollyyesterday at 12:53 AM3 repliesview on HN

I assume the author is talking about `fold`, as in `[A] -> B -> ((B,A) -> B) -> B`, and not what I often think of as reduce as `[A] -> ((A,A) -> A) -> A`.

`fold` is awesome and super useful. It's the easiest and most convenient way to turn a collection into a single value. Put me anecdotally in the opposite bucket.


Replies

nightpooltoday at 7:00 PM

I think part of the issue is that a lot of programming languages don't make a strong distinction between the two, and only provide the (more powerful) fold, but in a way that makes reduce operations harder to reason about (like OP said, with 0 types).

Associativity also makes fold hard. It's not super trivial to know when you might need e.g. left fold vs right fold

Chinjuttoday at 7:09 PM

These are pretty close to each other, to the point where I wouldn't bother strongly distinguishing them.

Suppose we have foldr as in [A] -> B -> ((A, B) -> B) -> B, foldl as in [A] -> B -> ((B, A) -> B) -> B, and reduce as in [A] -> ((A, A) -> A) -> A.

Then we have foldr list value operator = reduce [\b -> operator a b | a <- list] (.), foldl list value operator = foldr (reverse list) value (flip operator), and in the case of a finite non-empty list and associative operator, we have reduce list operator = foldr (tail list) (head list) operator = foldl (init list) (last list) operator.

So these are all basically slight re-parametrizations of each other.

wannabe44today at 6:19 PM

> `fold` is awesome and super useful. It's the easiest and most convenient way to turn a collection into a single value.

You will eventually learn about something called "for loop", and it will be nice.

show 2 replies