[Haskell-cafe] Textbook example of instance Foldable ((,) a)

John Beattie jkb at jkbsc.co.uk
Tue Nov 24 09:10:24 UTC 2020


On 2020-11-23 10:30 -0500, Sebastiaan Joosten wrote:
> length is part of the Foldable class:
> 
> length = foldl' (\c _ -> c+1) 0
> It is probably defined this way s.t. it satisfies:
> length = length . toList
> Not the actual definition, but you can read toList as:
> toList = foldr (:) []
> 
> So as soon as one defines foldr for pairs:
> 
> foldr f z (_, y) = f y z
> 
> We get:
> toList (a,b) = [b]
> 
> Using the 'natural' property: length = length . toList
> We obtain: length (a,b) = length [b] = 1
> 
> 
> On Mon, Nov 23, 2020 at 10:22 AM Manuel Schneckenreither <
> manuel.schnecki at gmail.com> wrote:
> 
>         >>>>> "HT" == Henning Thielemann <lemming at henning-thielemann.de>
>     writes:
> 
>         HT> "length (a,b) == 1" is only a consequence of defining instance
>         HT> Foldable for pairs. It was not the argument to implement that
>         HT> instance, at all.
> 
>     What was the argument to use 1, not 2 for instance?

ok, but why define foldr like that?

A long time ago, I saw an exposition of lists in an imperative setting which
treated them as pairs of (value, pointer) where the pointer pointed to the next
item. If we start with the above folder for pairs, I think we wouldn't get the
usual foldr on lists defined in this way from pairs, no?

Ok, I see, pairs are used for lots of things, including lists. They could also
be used as the basis for longer tuples.

Another suggestion, why don't we define foldr via currying:

foldr f z (x,y) = f z x y   ?


More information about the Haskell-Cafe mailing list