logoalt Hacker News

someonebaggy • today at 3:02 PM • 4 replies • view on HN

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?

Replies

bos • today at 3:45 PM

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.

s-zeng • today at 4:01 PM

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

➕ show 2 replies
chippiewill • today at 4:24 PM

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

tome • today at 5:12 PM

Or just use `for_` instead of explicit recursion ...