Functors and Applicatives
in JavaScript???

Let's talk about functions

a → b

Input an a, get out a b

Any input a will map to one output b

Q: When is a function not a function?

A: When it's a method

a, x?, y?, ... → b? c? void?

... something happened inside some object ...

... some side effects happened, maybe affecting state somewhere else?

... and then something returns ... right?

... well, I get the same output for the same input then, right?

Function: Immunize your cat

A function from Cat → Cat

Strictly speaking ...

Function: Immunize your ???

A function from Cat → Cat null → Shit

Digression: A few words about function composition

When you build up a functional pipeline, everybody has to play nice.

capitalize :: String → String

What if there is no element with the ID you input?

Functor: Immunize your Cat

n.b.: Same function from Cat → Cat

What the Functor

A functor is simply a function that lets you map over the contents of a container.

map :: (a → b) → Functor a → Functor b

So what?

Functor: Here's What--Immunize your ???

n.b.: Same function from Cat → Cat, now null safe!

Maybe Functor

Composing with the Maybe Functor

capitalize :: String → Maybe(String)

Some Other Functors



Validation, IO, Reader, Writer, State, Future, ...

Array is a Functor

map :: (a → b) → [a] → [b]

(Arrays are complected with the notion of iteration.)


n.b.: Same function from Cat → Cat, yet again!

Apply (Array)

Applies a function (or functions) in a container to a value (or values) in a container.

ap :: [f] → [a] → [f a]

Apply (Maybe)

Problem: Matching Strings

hasAbc :: [String] → Boolean



Wraps an arbitrary object in a container.

of :: x → [x]

hasAbc, take 2

What we want is a function hasAbc :: [String] → Boolean

Bibliography, Resources, & Further Reading

Hey Underscore, You're Doing It Wrong, Brian Lonsdorf (@drboolean)
Hardcore functional programming in Javascript, Leonardo Crespo
Favoring Curry, Scott Sauyet (@scott_sauyet)
Why Ramda, Scott Sauyet (@scott_sauyet)
Introducing Ramda, Michael Hurley (@buzzdecafe)
The Tao of λ: Applicatives, Ramda style, Michael Hurley (@buzzdecafe)
Fantasy-Land, Brian McKenna (@puffnfresh) et al.
Folktale, robotlolita (@robotlolita)
Ramda.js, Scott Sauyet & Michael Hurley

Illustrations courtesy of J. C. Phillipps (@jcphillipps)

No animals were harmed in the making of this presentation