[英]Haskell : Applicative Functor
I am new to Haskell. 我是Haskell的新手。 I've made a type Maybe3. 我做了一个类型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
How to make Maybe3 an applicative functor? 如何使Maybe3成为一个应用函子? And how to make it a Monad? 如何让它成为Monad?
My understanding is that Missing3
and Unknown3
work a bit like Nothing
, except they give a little more feedback about why there's no answer, so might behave slightly differently to each other. 我的理解是Missing3
和Unknown3
工作有点像Nothing
,除了他们提供了一些关于为什么没有答案的反馈,所以可能表现得彼此略有不同。 Certainly I think Missing3
should behave like Nothing
. 当然我认为Missing3
应该表现得像Nothing
。
Let's look at how these are defined for Maybe
: 让我们来看看这些是如何为Maybe
定义的:
Here's the Functor instance for Maybe
: 这是Maybe
的Functor实例:
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
I think it's clear how to deal with Missing3
and Unknown3
here. 我认为这里很清楚如何处理Missing3
和Unknown3
。
instance Monad Maybe where
(Just x) >>= k = k x
Nothing >>= _ = Nothing
(Just _) >> k = k
Nothing >> _ = Nothing
return = Just
fail _ = Nothing
You can't help but do the same here with >>=
for Missing3
and Unknown3
, since you don't have a value to bind with. 你不能不在这里使用>>=
for Missing3
和Unknown3
,因为你没有要绑定的值。 The only question is do you fail with Unknown3
or Missing3
? 唯一的问题是你用Unknown3
或Missing3
失败了吗?
Here's where there's a little more digging: 这里有更多挖掘的地方:
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) }
Now that translates to 现在转换为
mf <*> mx = do
f <- mf
x <- mx
return (f x)
Which you can use all the time to turn a Monad into an Applicative. 您可以随时使用Monad将Monad变为Applicative。
In fact, whenever you find yourself writing 事实上,每当你发现自己写作时
this thing = do
something <- some monadic thing
more <- some other thing
yetmore <- another thing too
return (combine something more yetmore)
you should rewrite it using applicative notation: 你应该使用applicative notation重写它:
this thing = combine <$> some monadic thing
<*> some other thing
<*> another thing too
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.