我是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
Run Code Online (Sandbox Code Playgroud)
如何使Maybe3成为一个应用函子?如何让它成为Monad?
我的理解是,Missing3与Unknown3工作有点像Nothing,但他们给,为什么没有答案有点更多的反馈,所以可能会略有不同的行为给对方.当然我认为Missing3应该表现得像Nothing.
让我们来看看这些是如何定义的Maybe:
这是Functor实例Maybe:
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
Run Code Online (Sandbox Code Playgroud)
我认为这是明确如何处理Missing3和Unknown3这里.
instance Monad Maybe where
(Just x) >>= k = k x
Nothing >>= _ = Nothing
(Just _) >> k = k
Nothing >> _ = Nothing
return = Just
fail _ = Nothing
Run Code Online (Sandbox Code Playgroud)
你不能不在这里使用>>=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) }
Run Code Online (Sandbox Code Playgroud)
现在转换为
mf <*> mx = do
f <- mf
x <- mx
return (f x)
Run Code Online (Sandbox Code Playgroud)
您可以随时使用Monad将Monad变为Applicative.
事实上,每当你发现自己写作时
this thing = do
something <- some monadic thing
more <- some other thing
yetmore <- another thing too
return (combine something more yetmore)
Run Code Online (Sandbox Code Playgroud)
你应该使用applicative notation重写它:
this thing = combine <$> some monadic thing
<*> some other thing
<*> another thing too
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
368 次 |
| 最近记录: |