Minminum value in a map haskell
dictionary, haskell
Solution
You'll need the constraint `Ord a`. Also, you need to decide how to compare `Just x` and `Nothing` (because you'll have to compare `(Just x, y)` with `(Nothing, z)`). I'll assume you want `Just x` to be smaller than `Nothing` for all `x`. If you use `toList` to covert the map to a list, you can then use `minimumBy` on the list with a custom comparison function. Moreover, the second part of the tuple (`Maybe b`) is irrelevant, so we'll just call consider `Map k (Maybe a, b)` and get a more general function.
I suggest something like
import qualified Data.Map as M
import Data.List
minimum' :: (Ord a) => M.Map k (Maybe a, b) -> k
minimum' = fst . (minimumBy comp) . M.toList
where
comp (_, (Nothing, _)) (_, (Just _, _)) = GT
comp (_, (Just _, _)) (_, (Nothing, _)) = LT
comp (_, (Nothing, _)) (_, (Nothing, _)) = EQ
comp (_, (Just x, _)) (_, (Just y, _)) = compare x y
It's hard to tell what kind of behavior you actually want with regards to the `Nothing`s, but another, more reasonable(*), alternative would be for the minimum function to have return type `Maybe k`, with `Nothing` returned in case the smallest element found (as above) is `(Nothing, _)`. One way to achieve this is to first `filter` the list returned by `toList` to eliminate all elements whose values are `(Nothing, _)`.
(*) Letting `Just x` be smaller than `Nothing` is kinda bad. You'll want the opposite behavior when looking for the largest element, so it all gets rather inconsistent and ugly. In other words, when the type `a` is ordered, the type `Maybe a` is only partially ordered (in a natural way -- of course you can force a total order, as above).
Problem
I have a question about how to retrieve the minimum value of a `Map`. I have a `Map k (Maybe a,Maybe b)` and I need to retrieve the key with the smallest value on the first element of the tuple (the smallest `a` ), but I couldn't find any predefined function. Is there some function I can use or I should implement that by myself? Thanks