I would like to express the following Haskell code, using only functor algebra (i.e. - not relying on any specific container type, such as List
):
ys = zipWith (+) (head xs : repeat 0)
(tail xs ++ [y])
It seems to me that there ought to be a way to do this, relying only on Foldable
(or, maybe, Traversable
), but I can't see it.
I'm wondering:
You can find the first or last element of a Foldable
using the First
or Last
monoids from Data.Monoid
.
foldMap (Last . Just) :: Foldable t => t a -> Last a
foldMap (First . Just) :: Foldable t => t a -> First a
All Foldable
are convertible to a list, and so because you can find the head and tail of a list, you can do so for any Foldable
.
toList = foldr (:) [] :: Foldable t => t a -> [a]
That said, the tail will have a list type and not that of the Foldable
(unless it was too a list). This is ultimately because not all that is Foldable
can implement an uncons. For example:
data Pair a = Pair a a
This is Foldable
, but you could not represent the tail of a Pair
using a Pair
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With