标准库中是否有 (a -> b) -> ((Maybe a) -> (Maybe b)) 转换器?

Is there (a -> b) -> ((Maybe a) -> (Maybe b)) converter in standard library?

我刚刚开始学习 Haskell,我发现自己正在为家庭作业编写这段代码:

eval :: ExprT -> Integer
eval (Lit x)    = x
eval (Add x y)  = (eval x) + (eval y)
eval (Mul x y)  = (eval x) * (eval y)

evalMayBe :: Maybe ExprT -> Maybe Integer
evalMayBe Nothing   = Nothing
evalMayBe (Just x)  = Just (eval x)

第二个功能似乎有点多余,所以我写了一个转换器:

toMayBe :: (a -> b) -> Maybe a -> Maybe b
toMayBe _ Nothing   = Nothing
toMayBe f (Just x)  = Just (f x)

并像

一样重写函数
evalMayBe :: Maybe ExprT -> Maybe Integer
evalMayBe = toMayBe eval

但后来我认为这个转换器似乎对很多不同的情况都非常有用,它一定在标准库中的某个地方 - 但是,我找不到它。

它在标准库中吗? "right" 编写这样的代码的方法是什么,您必须将函数链接到链中的值上,而这些值可能是 Maybe?

是的,这是fmap。将来您可以通过转储函数的类型 into Hoogle 为自己发现这种东西,这会给出 fmap 作为您建议的类型的第一个结果。