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.
There are four main types of different sequences you need to know, they are arithmetic sequences, geometric sequences, quadratic sequences and special sequences.
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.
Types of Sequence and SeriesArithmetic Sequences. Geometric Sequences. Harmonic Sequences. Fibonacci Numbers.
There are mainly three types of sequences: Arithmetic Sequences. Geometric Sequence. Fibonacci Sequence.
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]
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With