← Back to context

Comment by someonebaggy

8 hours ago

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?

If you don’t already know about folds, arguably yes.

If you do, then a quick glance at whether you’re using foldl’ or foldr tells you about what the function is allowed to do, which cuts down a little on comprehension.

List traversals are typically compact enough that there’s not a huge difference either way.

One advantage of using a fold, even in these cases, is that newcomers to Haskell often get so carried away with (and confused by) the power of pattern matching that they’ll write bizarre overly-complicated list traversals by hand, when a simpler mechanism exists that they just haven’t yet internalized.

There's a relatively popular point of view amongst Haskell programmers that explicit recursion is the goto of functional programming; a dedicated folding or traversing function provides more clarity on what exactly the function intends to do. The extreme end of this is recursion schemes and memes like zygohistomorphic prepomorphisms, which are almost certainly overkill on lists proper but might be useful when traversing bigger recursive structures. Personally, I almost always prefer to find a monoid to map the list elements into, and use `fold :: (Monoid m, Foldable t) => t m -> m`. It's essentially the equivalent of using `sum()` instead of `reduce()` in python

  • Every time I spend a lot of thought on a problem I always go back to F-Algebras and F-CoAlgebras.

    Most recursion is through fold and unfold

  • Folding 'fold' into contortions to use it as a generic List iterator does not "provide clarity".

    • In functional programming, there is no "generic list iterator", though. It matters what the output is, whether you need to look at the value of previous iterations, etc.

One of the links (on Fusion) points out that GHC in particular has a lot of optimizations and rewrite rules for folds and many Prelude functions written as simple recursion also include optimized fold representations to suggest to various stages of GHC's optimizer.

As with so many such topics it seems an interesting spectrum between clarity and/or aesthetics and potential performance optimizations. Especially because it often seems like one of those "learning curve flips the clarity/aesthetics preferences" because at some point of familiarity folds can be faster to read than trying to reason through an explicitly written recursion.

I think once you become comfortable with a fold, and of thinking in that manner, it actually becomes easier with a fold.