Haskell: sequenceA (explanation)

Context:

http://learnyouahaskell.com/functors-applicative-functors-and-monoids#applicative-functors

ctrl+f “Let’s give our function a whirl on some applicatives.”

A colleague was overcomplicating it a bit.

There isn’t really a need to manually evaluate sequenceA [(+1)] , and see what it does exactly “under the hood”.

The article does not bother to do that, and doing so kinda defeats the purpose of having the sequenceA abstraction in the first place: to reduce cognitive load.

(The article used a simpler example: sequenceA [Just 3, Just 2, Just 1] == Just [3,2,1] to illustrate the abstraction. Once you see the abstract pattern, there is no need to go “under the hood” for other applicative types.)

All that’s required to understand the behaviour of sequenceA [(+1)], is to see that:

  • the outer [] is a Foldable . In this case, this just means it’s a suitable container that can be used with sequenceA .
  • the inner (+1) is an Applicative . In this case, this means one can lift []’s constructor (i.e. (:)) into the (+1) .
  • sequenceA’s job is to deconstruct the outer container [], and reconstruct it inside the Applicative.

Then, knowing that (+1) == \r -> r + 1 , and reading the earlier part of the same article explaining how lifting works with this particular Applicative, it becomes clear that:

Similarly,

Abstractly,

— -

It gets even easier with do notation:

What? CHARMANDER is evolving!

What? CHARMELEON is evolving!

— -

Bonus: sample code

Try in GHCi: