15

I'm confused as to why I got this in GHCi

:t sequence [Just,Just]
sequence [Just, Just] :: a -> [Maybe a]

To elaborate, I can understand sequence [Just 1, Just 2] :: Num a => Maybe [a] because when looking at the type of sequence

sequence :: (Monad m, Traversable t) => t (m a) -> m (t a)

it is clear that this function takes a collection of monadic values and return a single monadic value of the collection. Thus, when we call sequence [Just 1, Just 2] we should get back a Just of [1,2]. Following that train of thoughts, shouldn't sequence [Just, Just] return a single Just?

Thanks.

1 Answer 1

24

The second sequence works in a different monad.

For the first:

sequence [Just 1, Just 2]

we have that Just 1 :: Maybe a and this is a value in the Maybe monad. Concretely, the type [Maybe a] is matched against t (m b) as required by sequence, and we get t ~ [], m ~ Maybe, b ~ a -- hence the Maybe monad.

For the second:

sequence [Just, Just]

we have that Just :: a -> Maybe a. Which monad is this in? Now the type [a -> Maybe a] is matched against t (m b), and we get t ~ [], m ~ (->) a, b ~ Maybe a -- hence we are now working in the (->) a monad, and no longer in the Maybe one.

In this (->) a monad, which is isomorphic to the Reader a monad, we have e.g.

sequence [f, g, h] = \x -> [f x, g x, h x]

Indeed, a computation with the (->) a monad is a computation "reading an implicit argument of type a". The sequence function simply turns a list of such computations ([(->) a b], i.e. [a -> b]) into a single computation that reads the implicit argument just once, and produces a list with all the results ((->) a [b], i.e. a -> [b]).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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