3

我有两个功能:

f :: a -> Maybe a
g :: a -> a

我想创建这样的功能:

h :: a -> Maybe a

h x
| isJust(f x) = Just (g $ fromJust(f x))
| otherwise   = Nothing

我怎样才能以更优雅的方式做到这一点?

4

3 回答 3

12

由于您已使用标记了此问题:

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' 的返回类型不正确。

于 2015-12-25T22:56:41.367 回答
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可用于代替(.).

于 2015-12-25T23:01:49.857 回答
4

为什么不简单地这样做:

h :: a -> Maybe a
h x = fmap g (f x)

或运营商版本:

h :: a -> Maybe a
h x = g <$> f x
于 2015-12-25T22:51:14.890 回答