我正在学习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
但是后来我认为这个转换器在许多不同情况下似乎都非常有用,以至于它必须存在于标准库中的某个位置-但是,我找不到它。
它在标准库中吗?像这样编写代码的“正确”方法是什么,在这种方法中,您必须将函数链接到值可能是Maybe的链中?