[Haskell-beginners] Explanation of composite with foldl
Lawrence Bottorff
borgauf at gmail.com
Wed Jan 13 21:09:35 UTC 2021
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?
Likewise with this
lastbut1safe :: Foldable f => f a -> Maybe a
lastbut1safe = fst . foldl (\(a,b) x -> (b,Just x)) (Nothing,Nothing)
What's happening with the type definition?
LB
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20210113/524197ce/attachment.html>
More information about the Beginners
mailing list