我想将以下函数映射到Map
的键上
f :: a -> Maybe b
并丢弃Nothing
key 并保留Just
key ,但是从Just
中提取了这些 key 。就像Map.mapMaybe
一样,但是对于 key mapMaybeKeys :: (a -> Maybe b) -> Map a c -> Map b c
我在Hoogle中搜索了这种类型的签名,但没有找到任何东西。我可以这样做:
mapMaybeKeys f
= Map.toList
. catMaybes
. fmap (fmap swap . traverse f . swap)
. Map.toList
或者:mapMaybeKeys f
= Map.mapKeys fromJust
. Map.delete Nothing
. Map.mapKeys f
有没有更优雅的方式? 最佳答案
有了列表理解,
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 ]
关于haskell - mapMaybe用于Data.Map中的键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63364264/