5

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.

The Unfun Cat
  • 29,987
  • 31
  • 114
  • 156
  • Also, the function above fails when xs is the empty list, but even I should be able to fix that eventually. – The Unfun Cat May 23 '16 at 18:54
  • 1
    See this question for different ways to accomplish this (obviously just replace max with min): http://stackoverflow.com/questions/12216886/monoid-mempty-in-pattern-matching – Free_D May 23 '16 at 20:51

2 Answers2

5

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) 
Lee
  • 142,018
  • 20
  • 234
  • 287
  • Thanks, this was my first attempt but I added a `maybeMin Nothing Nothing` which made it not compile. D'oh. – The Unfun Cat May 23 '16 at 19:34
  • 2
    @TheUnfunCat One thing you might find helpful are typed holes. If you write `mini :: (Foldable t, Ord a) => t a -> Maybe a; mini xs = foldr _ Nothing xs`, GHC will tell you the type of the value that should go where the `_` is. – David Young May 24 '16 at 03:22
-1

You could try by replacing 'X' with the first element on the list. Of course you should now deal with the case when the function 'mini' gets invoked with an empty list.