我有两个功能:
f :: a -> Maybe a
g :: a -> a
我想创建这样的功能:
h :: a -> Maybe a
h x
| isJust(f x) = Just (g $ fromJust(f x))
| otherwise = Nothing
我怎样才能以更优雅的方式做到这一点?
答案 0 :(得分:13)
由于您使用dot-operator标记了此问题:
h :: a -> Maybe a
h = fmap g . f
有关解释:
f :: a -> Maybe a
g :: a -> a
fmap g :: Maybe a -> Maybe a
(.) :: (Maybe a -> Maybe a) -> (a -> Maybe a) -> (a -> Maybe a)
(.) (fmap g) :: (a -> Maybe a) -> (a -> Maybe a)
fmap g . f :: (a -> Maybe a)
h :: a -> Maybe a
请注意,(.)
和fmap g
的类型实际上更为通用:
(.) :: (b -> c) -> (a -> b) -> (a -> c)
-- b in this case is Maybe a
-- c in this case is Maybe a
fmap g :: Functor f => f a -> f a
-- f in this case is Maybe
但是,您也可以对f
的结果进行模式匹配:
h x =
case f x of
Just k -> Just (g k)
_ -> Nothing
请注意,您的原始示例甚至无法编译,因为g
的返回类型不正确。
答案 1 :(得分:5)
具有
fmap2 :: (Functor g, Functor f) => (a -> b) -> g (f a) -> g (f b)
fmap2 = fmap . fmap
这是一个有趣的方式:
h :: a -> Maybe a
h = fmap2 g f
fmap2 g f ~> fmap (fmap g) f ~> fmap g . f ~> \x -> fmap g (f x)
此处使用了Functor ((->) r)
个实例:fmap
可以代替(.)
使用。
答案 2 :(得分:4)
为什么不简单:
h :: a -> Maybe a
h x = fmap g (f x)
或运营商版本:
h :: a -> Maybe a
h x = g <$> f x