Explanation of composite with foldl

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Explanation of composite with foldl

Lawrence Bottorff-2
I see this on the Haskell 99 questions 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

_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: Explanation of composite with foldl

Francesco Ariis
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
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners