I want to implement minimum with foldr or foldMap. According to the exercise, it should have this definition:
mini :: (Foldable t, Ord a) => t a -> Maybe a -- named "mini" to avoid name clash
It sounded pretty straightforward, but I do not know what I can substiture for X below to make it work. Help please?
mini xs = Just (foldr min X xs)
And you get bonus points for showing me how to do it with foldMap too, but that seems harder.
Haskell Wiki compares foldr , foldl and foldl' and recommends using either foldr or foldl' . foldl' is the more efficient way to arrive at that result because it doesn't build a huge thunk.
The Foldable type class provides a generalisation of list folding ( foldr and friends) and operations derived from it to arbitrary data structures.
You could do:
mini :: (Foldable f, Ord a) => f a -> Maybe a
mini = foldr maybeMin Nothing
where
maybeMin x Nothing = Just x
maybeMin x (Just y) = Just (min x y)
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