[Haskell-beginners] Monad for Pair
Marcin Mrotek
marcin.jan.mrotek at gmail.com
Tue Nov 17 22:15:37 UTC 2015
Hello,
I'm pretty sure a Pair (like any other fixed-length type, besides the
corner case of a single field like in Writer, Identity, etc) can't be
a monad. Perhaps instead of struggling with >>=, consider join. It has
a type:
join :: Monad m => m (m a) -> m a
for Pairs that would be
join :: Pair (Pair a) -> Pair a
join (Pair (Pair a1 a2) (Pair b1 b2)) = Pair _ _
How do you want to fit four values into two boxes? You cannot place
any constraints on the type inside the pair, so it can't be a monoid
or anything that would let you combine the values somehow. You could
only choose two of the values and drop the other two on the floor.
Getting back to >>=, it's assumed to follow these laws:
1) return a >>= k = k a
2) m >>= return = m
3) m >>= (\x -> k x >>= h) = (m >>= k) >>= h
As for the firs, return a = Pair a a. Then the first two laws become
1) Pair a a >>= k = k a
2) Pair a b >>= (\a -> Pair a a) = Pair a b
The first law could work if >>= just chose one of the values
arbitrarily. But the second law is a hopeless case. You would need to
pick one element of a pair, plug it into a function that repeats the
argument, and somehow get back the other element that you've already
dropped.
Concluding, either I'm sorely mistaken or there indeed isn't a Monad
instance for Pair.
Best regards,
Marcin Mrotek
More information about the Beginners
mailing list