我是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
:
这是Functor实例Maybe
:
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
您不能>>=
为forMissing3
和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变成Applicative。
事实上,只要您发现自己在写作
this thing = do
something <- some monadic thing
more <- some other thing
yetmore <- another thing too
return (combine something more yetmore)
您应该使用适用的符号将其重写:
this thing = combine <$> some monadic thing
<*> some other thing
<*> another thing too
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句