I'm reading Graham Hutton book on Haskell, and don't no how to proceed in one part of an excercise. The excercise says as follows:
Given the following type 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 Functor, Applicative and Monad classes. With the aid of an example, explain what the >>=
operator for this type does.
I have had problems defining the <*>
operator of Applicative. The type of <*>
is:
(<*>) :: Expr (a -> b) -> Expr a -> Expr b
I don't understand how (Val n) <*> mx
might work, because theoretically I need to provide a Expr b
, but all I have is a Expr a
and no function to convert (a -> b
).
I also don't understand what to do in the (Add l r) <*> mx
case.
This is my implementation.
instance Functor Expr where
--fmap :: (a -> b) -> Expr a -> Expr b
fmap g (Var x) = Var (g x)
fmap g (Val n) = Val n
fmap g (Add l r) = Add (fmap g l) (fmap g r)
instance Applicative Expr where
--pure :: a -> Expr a
pure = Var
-- <*> :: Expr (a -> b) -> Expr a -> Expr b
(Var g) <*> mx = fmap g mx
--(Val n) <*> mx = ???
--(Add l r) <*> mx = ???
instance Monad Expr where
-- (>>=) :: Expr a -> (a -> Expr b) -> Expr b
(Var x) >>= g = g x
(Val n) >>= g = Val n
(Add l r) >>= g = Add (l >>= g) (r >>= g)
expr = Add (Add (Var 'a') (Val 4)) (Var 'b')
Finally, I have a doubt with respect to the >>= in the monad. The idea of this operator is to do things like substituting variables? Like:
expr >>= (\x -> if x == 'a' then Val 6 else Var x) >>= (\x -> if x == 'b' then Val 7 else Var x)
(Val n) <*> mx
, what's the type ofn
? (note the type of<*>
) – CarbideVar
... – CarbideVal k <*> _ = Val k
and_ <*> Val k = Val k
which give different results for an expression likeVal 0 <*> Val 1
. – Rachellrachelle