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
You’ll need the constraint
Ord a. Also, you need to decide how to compareJust xandNothing(because you’ll have to compare(Just x, y)with(Nothing, z)). I’ll assume you wantJust xto be smaller thanNothingfor allx. If you usetoListto covert the map to a list, you can then useminimumByon the list with a custom comparison function. Moreover, the second part of the tuple (Maybe b) is irrelevant, so we’ll just call considerMap k (Maybe a, b)and get a more general function.I suggest something like
It’s hard to tell what kind of behavior you actually want with regards to the
Nothings, but another, more reasonable(*), alternative would be for the minimum function to have return typeMaybe k, withNothingreturned in case the smallest element found (as above) is(Nothing, _). One way to achieve this is to firstfilterthe list returned bytoListto eliminate all elements whose values are(Nothing, _).(*) Letting
Just xbe smaller thanNothingis 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 typeais ordered, the typeMaybe ais only partially ordered (in a natural way — of course you can force a total order, as above).