[Haskell-beginners] Monad for Pair

Gesh gesh at gesh.uni.cx
Wed Nov 18 08:59:10 UTC 2015

On November 18, 2015 12:15:37 AM GMT+02:00, Marcin Mrotek <marcin.jan.mrotek at gmail.com> wrote:
>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
>Concluding, either I'm sorely mistaken or there indeed isn't a Monad
>instance for Pair.
>Best regards,
>Marcin Mrotek
>Beginners mailing list
>Beginners at haskell.org

No. Pair can be made into a monad, and this is made clear by realizing that Pair a ~ Bool -> a, so the monad instance for Reader should work here. In fact, this means that any representable functor (i.e. f s.t. f a ~ t-> a for some t) has all instances that Reader r has for fixed r.

More information about the Beginners mailing list