fmap的反面是什么?

What is the reverse of fmap?

我有一个仿函数链,我需要在某个时候将我的值包装在 Maybe:

module Funct where 
(>>?) :: Maybe a -> (a -> Maybe b) -> Maybe b
(Just a) >>? f = f a
Nothing >>? _ = Nothing


f1 :: Int -> Maybe Bool
f1 a = if a > 2 then Just (a `mod` 2 == 0)  else Nothing

f2 :: Bool ->  Char
f2 b = if b then 'a' else 'b'

f3 :: Char -> Maybe Int
f3 c = if c == 'a' then Just 1 else Nothing

fm :: Int -> Maybe Int
fm x = f1 x >>? f2  >>? f3
                 ^ 
                 Is there a reverse method for fmap particular for Maybe 
                 or do I have to implement it?

已实施

myWrapper :: Char->Maybe Char
myWrapper c = Just c

fm x = f1 x >>? myWrapper . f2 >>? f3  -- is there any built in way more concise?

我问是因为在链接时我想你也需要其他 monad 的包装器,比如 Either

(is there any built in way more concise?)

当然可以:

myWrapper = Just

或内联:

fm x= f1 x>>? Just . f2 >>? f3

数据构造函数可以看作普通函数,因此您可以将它们与其他函数组合。

(<&>) = flip fmap,与(>>=)具有相同的优先级:

fm x = f1 x <&> f2 >>= f3

I am asking because when chaining I suppose you would need wrappers for other monads too like Either.

正确。 MaybeEither 这样的每个类型构造函数都需要对 >>=return 这样的东西有自己的定义,但这正是类型类的实例:类型类的定义专门用于特定类型构造函数的方法。例如,

class Monad m where
    return :: a -> m a
    (>>=) :: m a -> (a -> m b) -> m b

instance Monad Maybe where
    return = Just
    Nothing >>= _ = Nothing
    (Just x) >>= f = f x

-- This looks similar to the Maybe instance because in some sense,
-- Maybe is just a special case of Either: Maybe ~ Either ()
instance Monad (Either a) where
    return = Right
    (Left x) >>= _ = Left x
    (Right x) >>= f = f x

你的 fm 函数可以以适用于 any monad 的方式编写,而不仅仅是 Maybe:

fm :: Maybe m => Int -> m Int
fm x = f1 x >>= return . f2  >>= f3