[Haskell-beginners] Explanation of composite with foldl

Francesco Ariis fa-ml at ariis.it
Wed Jan 13 21:33:51 UTC 2021


Il 13 gennaio 2021 alle 15:09 Lawrence Bottorff ha scritto:
> I see this on the Haskell 99 questions
> <https://wiki.haskell.org/99_questions/Solutions/2> which will return the
> second-from-last element of a list
> 
> lastbut1 :: Foldable f => f a -> a
> lastbut1 = fst . foldl (\(a,b) x -> (b,x)) (err1,err2)
>   where
>     err1 = error "lastbut1: Empty list"
>     err2 = error "lastbut1: Singleton"
> 
> I understand how the code works, but not the significance of the type
> declaration. That looks like a type class. It works without it, I believe.
> Why have we used Foldable type class?

A `Foldable` constraint will make the function work on a plethora of
types [1] apart from lists (e.g. Arrays, etc.).

The assignment is clearly monomorphic («Find the last but one element of
a list.»), I would have preferred a `:: [a] -> a` signature.

[1] https://hackage.haskell.org/package/base-4.14.1.0/docs/Data-Foldable.html#t:Foldable


More information about the Beginners mailing list