I have a data type that resembles Blah
below but because of a quirk with the type I cannot automatically derive Functor, Applicative, and Monad. So I must do it manually, but I'm not sure how. I tried to take inspiration from the instances for ((->) a)
, but I can't quite figure out the Monad instance.
newtype Blah a = Blah (String -> a) -- deriving (Functor, Applicative, Monad)
-- this seems right
instance Functor Blah where
fmap f (Blah g) = Blah (f . g)
instance Applicative Blah where
pure = Blah . const
-- This is right, right?
(<*>) (Blah f) (Blah g) = Blah $ \x -> f x (g x)
instance Monad Blah where
return = pure
-- I'm not having any luck here.
(>>=) a b = Blah $ \c -> _
Edit: Someone marked this as a duplicate of another, but I don't see where I would've gotten the answer from that. The newtype wrapper is what made this difficult. I looked up the Monad
instance in base for (->) a
before I wrote this question, but the gymnastics in the answer here are what I needed.
How about
Blah f >>= g = Blah $ \s ->
let Blah h = g $ f s in h s