Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapMaybe for keys in Data.Map

Tags:

haskell

I want to map the following function over the keys of a Map

f :: a -> Maybe b

and discard the Nothing keys and keep the Just keys, but extracted from the Just. Just like Map.mapMaybe, but for keys

mapMaybeKeys :: (a -> Maybe b) -> Map a c -> Map b c

I searched Hoogle for this type signature but didn't find anything.

I could do this:

mapMaybeKeys f
    = Map.toList
    . catMaybes
    . fmap (fmap swap . traverse f . swap)
    . Map.toList

or:

mapMaybeKeys f
   = Map.mapKeys fromJust
   . Map.delete Nothing
   . Map.mapKeys f

Is there a more elegant way?

like image 839
bwroga Avatar asked Aug 11 '20 18:08

bwroga


1 Answers

With list comprehensions,

import Data.Map (Map)
import qualified Data.Map as M
import Control.Arrow (first)

mapMaybeKeys :: Ord b => (a -> Maybe b) -> Map a c -> Map b c
mapMaybeKeys f m = 
   M.fromList [ (b,a) | (Just b, a) <- map (first f) . M.toList $ m ]
like image 92
Will Ness Avatar answered Oct 10 '22 16:10

Will Ness