Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement minimum with foldr (or foldMap)?

Tags:

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.

like image 302
The Unfun Cat Avatar asked May 23 '16 18:05

The Unfun Cat


People also ask

Is Foldr or Foldl more efficient?

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.

What is the foldable Typeclass used for?

The Foldable type class provides a generalisation of list folding ( foldr and friends) and operations derived from it to arbitrary data structures.


1 Answers

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) 
like image 160
Lee Avatar answered Sep 28 '22 01:09

Lee