Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance of Monad for Multiple Data Constructors

Tags:

haskell

monads

I've started Haskell not too long ago, and am now teaching myself about monads, so I've come up with a dumb example for myself here to assist me in understanding an aspect of monads.

Given a type Certainty defined as

data Certainty a = Definitely a | Perhaps a | Nope

and an instance of Monad for said type

instance Monad Certainty where
  return = ...

how would the method return be defined for Certainty and each of its data constructors?

like image 914
Mona the Monad Avatar asked Jun 06 '26 01:06

Mona the Monad


1 Answers

you have to pick one - based on the naming I would suggest

return value = Definitely value

remember that return a >>= f must be f a

bind should probably be

(Definitely a) >>= f = f a
(Perhaps a)    >>= f = case f a of
                          Definitely b -> Perhaps b
                          Perhaps b    -> Perhaps b
                          Nope         -> Nope
Nope           >>= _ = Nope
like image 65
Random Dev Avatar answered Jun 08 '26 22:06

Random Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!