在monad中映射

时间:2015-11-03 18:39:22

标签: haskell monads

f1 ∷ Int → Identity (Maybe String)
f1 x = Identity $ if even x then Just (show x) else Nothing

-- f1 4 = "4", f1 5 = Nothing etc.

f2 ∷ (Int → Identity (Maybe String)) → [Int] → Identity String

-- f2 [1..10] = "246810"

现在可以使用mapMaybeM实现f2吗?

---编辑----------------------

让我试着告诉你这个问题背后的实际问题。

g1 :: Type1 -> SomeT Maybe Type2

g2需要映射Just值并摆脱Maybe:

g2 :: (Type1 -> SomeT Maybe Type2) -> [Type1] -> SomeT Identity [Type2]

1 个答案:

答案 0 :(得分:2)

mapMaybeM f1会让你[Int] -> Identity [String]。然后,您可以使用fmap concat Identity [String] -> Identity String来连接值。

根据您的更新,如果有帮助:

f2 :: (Int -> IdentityT Maybe String) -> [Int] -> IdentityT Identity [String]
f2 f = mapIdentityT (fmap concat) . foldl (liftA2 (++)) (lift (return [])) . map (mapIdentityT (return . maybeToList) . f)

这可以在IdentityT内依赖mapIdentityT。我认为根本问题是[MT M a] -> MT M [a],我不确定这是否可能 - 它可能取决于变压器的属性。