繁体   English   中英

Haskell:Applicative Functor

[英]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?

关键的想法

我的理解是Missing3Unknown3工作有点像Nothing ,除了他们提供了一些关于为什么没有答案的反馈,所以可能表现得彼此略有不同。 当然我认为Missing3应该表现得像Nothing

让我们来看看这些是如何为Maybe定义的:

函子

这是Maybe的Functor实例:

instance  Functor Maybe  where
    fmap _ Nothing       = Nothing
    fmap f (Just a)      = Just (f a)

我认为这里很清楚如何处理Missing3Unknown3

单子

instance  Monad Maybe  where
    (Just x) >>= k      = k x
    Nothing  >>= _      = Nothing

    (Just _) >>  k      = k
    Nothing  >>  _      = Nothing

    return              = Just
    fail _              = Nothing

你不能不在这里使用>>= for Missing3Unknown3 ,因为你没有要绑定的值。 唯一的问题是你用Unknown3Missing3失败了吗?

合用的

这里有更多挖掘的地方:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM