Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble understanding the type of sequence [Just, Just]

Tags:

haskell

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.

like image 595
Lim H. Avatar asked Dec 12 '15 20:12

Lim H.


People also ask

What are the 4 types of sequence?

There are four main types of different sequences you need to know, they are arithmetic sequences, geometric sequences, quadratic sequences and special sequences.

How do you identify a sequence type?

An arithmetic series is one where each term is equal the one before it plus some number. For example: 5, 10, 15, 20, … Each term in this sequence equals the term before it with 5 added on. In contrast, a geometric sequence is one where each term equals the one before it multiplied by a certain value.

What are the 5 types of sequence?

Types of Sequence and SeriesArithmetic Sequences. Geometric Sequences. Harmonic Sequences. Fibonacci Numbers.

What are the 3 types of sequences?

There are mainly three types of sequences: Arithmetic Sequences. Geometric Sequence. Fibonacci Sequence.


1 Answers

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]).

like image 134
chi Avatar answered Oct 13 '22 23:10

chi