2

Consider the next piece of code -

module Main where

data MyTree a = MyLeaf a
              | MyNode (MyTree a) (MyTree a)
              deriving (Show)

instance Monad MyTree where
   return = MyLeaf
   (MyLeaf x) >>= f = f x
   (MyNode x y) >>= f = MyNode (x >>= f) (y >>= f)

main :: IO ()
main  =
   do

      let tree1 = MyNode (MyLeaf 3) (MyNode (MyLeaf 4) (MyLeaf 5))
      let tree2 = MyNode (MyLeaf "ABC") (MyNode (MyLeaf "DEFG") (MyLeaf "HIJKL"))

      print (tree1 >>= (\x -> MyLeaf (x+200)))
      print (tree2 >>= (\x -> MyLeaf (tail x)))

I try to simply implement a Tree Monad, but the problem is when i compile the code above, i get the following errors:

* No instance for (Applicative MyTree)
    arising from the superclasses of an instance declaration
* In the instance declaration for `Monad MyTree'

I dont understand what's missing. What's the point in having Applicative?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • When all you need is `Ord`, why are you required to implement `Eq` as well? After all you could always define `a == b = not (a < b) && not (a > b)`. Same thing here. Just a requirement to define `pure = return` and `(<*>) = ap`. cf. https://stackoverflow.com/questions/24112786/why-should-applicative-be-a-superclass-of-monad – Will Ness Dec 06 '17 at 15:35

0 Answers0