Typeclassopedia presents the following exercise:

Maybe can easily be made an instance of Applicative; writing such an instance is left as an exercise for the reader.

Here's my implementation:

data Option a = Some a 
                | None deriving Show

instance Functor Option where
   fmap _ None     = None
   fmap f (Some x) = Some (f x)

instance Applicative Option where
   pure x                = Some x
   (Some f) <*> (Some x) = Some (f x) 
   _ <*> _               = None  

How does this look? In particular, I'm curious if the second line of the Applicative Option looks good.

Should I be using fmap on the right-hand side instead of Some (f x)?


Looks good, follows the laws of Applicative AFAICT, and I'd leave it like this, with fmap you'd need to write more.

  • \$\begingroup\$ But, by using fmap, I'd be re-using already written code - for Functor Option. Isn't that a meaningful code re-use? \$\endgroup\$ – Kevin Meredith Dec 1 '14 at 22:29
  • \$\begingroup\$ Compare fmap f (Some x) with Some (f x), I'd argue that the latter one is easier to understand, which is more important than reuse IMO. If you had that twice or more times in a row I'd agree. \$\endgroup\$ – ferada Dec 2 '14 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.