[Haskell-cafe] Improving the docs (specifically Data.Foldable)

Anthony Clayden anthony.d.clayden at gmail.com
Sat Oct 2 06:22:29 UTC 2021

At  *Fri Oct 1 01:42:39 UTC 2021*  Ben Franksen wrote

>> Am 17.09.21 um 07:15 schrieb Michael Turner:>> >>* "The contribution of each element to the final result is combined with an
*>>*     accumulator via an /operator/ function.  The operator may be explicitly
*>>*     provided by the caller as in `foldr` or may be implicit as in
`length`. In
*>>*     the case of `foldMap`, the caller provides a function mapping
each element
*>>*     into a suitable 'Monoid', which makes it possible to merge
the per-element
*>>*     contributions via that monoid's `mappend` function."
*> >>* This is a little better, but I'd write it this way, I think.
*>> >>* "Folds take operators as arguments. In some cases, it's implicit, as
*>>* in the function "length". These operators are applied to elements when
*>>* lazy evaluation requires it, with a fold 'accumulator' as one of the
*>>* operands. 'foldMap' uses a function (implicit? explicit?) that maps
*>>* elements into . . . ."
> The problem you two are both facing is this: you want to describe,
> abstractly, generally, the common principle behind an ad-hoc
> lumped-together set of functions. This is very likely to result in
> contortions and provides you with no insight.

I think neither "ad-hoc" nor "lumped-together" is accurate.

For both `Functor t` and `Foldable t` the metaphor is `t` as container.

* For `Functor` we wish to preserve the shape/spine and mangle each
element irrespective of other content.

* For `Foldable` we wish to throw away the shape/spine and return some
characteristic of the contents-as-a-whole.

(The fold is possibly returning another container/contents, but it
won't necessarily be the same `t`; even if it is, the result won't be
the same shape/spine.)

There are some frequent use-cases for "characteristic of the
contents-as-a-whole": count, sum, min/max, is-element. So it makes
sense to provide (possibly optimised) methods. Yes the insight is that
there's a common principle. But the optimising devil is in the detail.

The devilish detail is that although we're going to throw away the
shape/spine, knowing its organising principle will help navigating it
effectively. Otherwise we could stick with List as container -- but as
Ref [1] points out, that's hardly ever wise.

For somebody coming to the docos to generate their own `instance
Foldable`, thinking in terms of `toList` might help in getting the
right result; it won't explain why they'd want to use something other
than a List.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20211002/49830a00/attachment.html>

More information about the Haskell-Cafe mailing list