Haskell: The Applicative Method

I am new to Haskell. I made type 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? And how to make it a monad?

+3
source share
1 answer

main idea

I understand that Missing3they Unknown3work a bit like Nothingthat, except that they give a little more feedback on why there is no answer, so they can behave somewhat differently to each other. Of course, I think I Missing3should behave like that Nothing.

Let's see how they are defined for Maybe:

Functor

Here's a functor instance for Maybe:

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

I think that here it is clear how to deal with Missing3and Unknown3here.

Monad

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

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

    return              = Just
    fail _              = Nothing

>>= 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 .

, .

, ,

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
+5

All Articles