[Haskell-beginners] Monad for Pair
Marcin Mrotek
marcin.jan.mrotek at gmail.com
Thu Nov 19 18:56:39 UTC 2015
> Thanks for this - I’ll work through it.
Yeah, apparently I accidentaly wrote a correct instance there. You can
also use what Gesh wrote, and try to derive an instance from something
like:
tabulate :: (Bool -> a) -> Pair a
tabulate f = Pair (f True) (f False)
index :: Pair a -> Bool -> a
index (Pair a _) True = a
index (Pair _ b) False = b
instance Applicative Pair where
pure = tabulate . pure
fp <*> fa = tabulate $ index fp <*> index fa
instance Monad Pair where
m >>= f = tabulate $ index m >>= index . f
The instances for a function are (in pseudo-Haskell, I don't think GHC
accepts (a ->) instead of ((->) a), but it looks cleaner that way)
instance Applicative (a ->) where
pure = const
f <*> g = \x -> f x (g x)
instance Monad (a ->) where
f >>= k = \ r -> k (f r) r
> My wife once dreamt she was a C compiler - go figure… C !!??
C isn't exactly known for type safety, so things can indeed get
Kafkaesque sometimes.
Best regards,
Marcin Mrotek
More information about the Beginners
mailing list