[英]Haskell : Applicative Functor
我是Haskell的新手。 我做了一个类型Maybe3。
data Maybe3 a= Just3 a| Unknown3 | Missing3 deriving (Show, Eq, Ord)
eq3 :: Eq a => Maybe3 a-> Maybe3 a-> Bool3
eq3 Unknown3 _ = Unk3
eq3 Missing3 _ = False3
eq3 _ Missing3 = False3
eq3 _ Unknown3 = Unk3
eq3 (Just3 a) (Just3 b)=if a==b then True3 else False3
如何使Maybe3成为一个应用函子? 如何让它成为Monad?
我的理解是Missing3
和Unknown3
工作有点像Nothing
,除了他们提供了一些关于为什么没有答案的反馈,所以可能表现得彼此略有不同。 当然我认为Missing3
应该表现得像Nothing
。
让我们来看看这些是如何为Maybe
定义的:
这是Maybe
的Functor实例:
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
我认为这里很清楚如何处理Missing3
和Unknown3
。
instance Monad Maybe where
(Just x) >>= k = k x
Nothing >>= _ = Nothing
(Just _) >> k = k
Nothing >> _ = Nothing
return = Just
fail _ = Nothing
你不能不在这里使用>>=
for Missing3
和Unknown3
,因为你没有要绑定的值。 唯一的问题是你用Unknown3
或Missing3
失败了吗?
这里有更多挖掘的地方:
instance Applicative Maybe where
pure = return
(<*>) = ap
ap :: (Monad m) => m (a -> b) -> m a -> m b
ap = liftM2 id
liftM2 :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 f m1 m2 = do { x1 <- m1; x2 <- m2; return (f x1 x2) }
现在转换为
mf <*> mx = do
f <- mf
x <- mx
return (f x)
您可以随时使用Monad将Monad变为Applicative。
事实上,每当你发现自己写作时
this thing = do
something <- some monadic thing
more <- some other thing
yetmore <- another thing too
return (combine something more yetmore)
你应该使用applicative notation重写它:
this thing = combine <$> some monadic thing
<*> some other thing
<*> another thing too
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.