简体   繁体   中英

Exercise with functor, applicative and monads in Haskell

I'm doing exercises from the book "Programming in Haskell (2nd Edition)" and I have some problems in understanding the following:

"Given the following type of expressions

data Expr a = Var a | Val Int | Add (Expr a) (Expr a)
deriving Show

that contain variables of some type a , show how to make this type into instances of the Functor , Applicative and Monad classes. With the aid of an example, explain what the >>= operator for this type does."

I found a solution to the first question, which is the same as here: https://github.com/evturn/programming-in-haskell/blob/master/12-monads-and-more/12.05-exercises.hs (ex. 7), that is type correct.

The problem is that I cannot find out the sense of this exercise and the meaning of what this solution actually does.

To understand the solution, you need to get an intuition over a Functor , an Applicative and a Monad .

That being said fmap , <*> and >>= is just a way for one to be able to transform a data within an arbitrary F in your case that's an Expr from a -> b

Take a look at the Type class definitions of Functor , Applicative and Monad for example.

class Functor f where
    fmap :: (a -> b) -> f a -> f b

class Functor f => Applicative f where
    <*> :: f (a -> b) -> f a -> f b

class Applicative m => Monad m where
    >>= :: m a -> (a -> m b) -> m b

Though on the bigger picture, these functions also execute effects of the algebraic datatype that have the type class instances for it.

For example, I will provide the rough definition of the Maybe monad.

instance Monad Maybe where
    (Just something) >>= f = f something
    Nothing          >>= _ = Nothing

In this context, the bind or >>= combinator returns Nothing if there is Nothing for the input else it applies the arbitrary f on something such that f is a transformation from a -> Maybe b which satisfies the definition of the >>= combinator which is ma -> (a -> mb) -> mb where m is the Maybe datatype.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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