我必须实现一个功能maybemap
它具有(类似于功能图)一个功能
f :: a -> b
它应该适用于列表类型Maybe a
并给出一个列表Maybe b
maybemap :: (a -> b) -> [Maybe a] -> [Maybe b]
我将如何定义maybemap
函数?
我必须实现一个功能maybemap
它具有(类似于功能图)一个功能
f :: a -> b
它应该适用于列表类型Maybe a
并给出一个列表Maybe b
maybemap :: (a -> b) -> [Maybe a] -> [Maybe b]
我将如何定义maybemap
函数?
您可以只使用Maybe
的仿函数实例,其定义如下:
fmap :: (a -> b) -> Maybe a -> Maybe b -- fmap's type for Maybe
fmap f Nothing = Nothing
fmap f (Just a) = Just (f a)
使用它,您的函数可以这样定义:
maybemap :: (a -> b) -> [Maybe a] -> [Maybe b]
maybemap f = map (fmap f)
最简单的解决方案,正如它所提到的,
maybemap :: (a -> b) -> [Maybe a] -> [Maybe b]
maybemap = map . fmap
但总的来说,它是更通用的功能:
maybemap :: Functor f => (a -> b) -> [f a] -> [f b]
如我们所见,list也是一个函子,所以我们可以重写
fmap2 :: (Functor f, Functor g) => (a -> b) -> g (f a) -> g (f b)
fmap2 = fmap . fmap
并测试:
> fmap2 (++"!") [Nothing,Just"u"]
[Nothing,Just "u!"]
更新
中最有趣的fmap2
,它(.)
也是a -> b
函数的 Functor,并且fmap
是具有相同签名的函数:f a -> f b
. 我们的函数只能包含fmap
s:
fmap2 = fmap fmap fmap