05.03.2016 Views

Programming in Scala”

fpiscompanion

fpiscompanion

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter notes 40<br />

apply(u, unit(y)) == apply(unit(_(y)), u)<br />

This law is essentially say<strong>in</strong>g that unit is not allowed to carry an effect with regard to any<br />

implementation of our applicative functor. If one argument to apply is a unit, then the other can<br />

appear <strong>in</strong> either position. In other words, it should not matter when we evaluate a unit.<br />

Composition<br />

The composition law for apply is stated as:<br />

apply(u, apply(v, w)) == apply(apply(apply(unit(f => g => f compose g), u), v), w)<br />

This is say<strong>in</strong>g that apply<strong>in</strong>g v to w and then apply<strong>in</strong>g u to that is the same as apply<strong>in</strong>g composition<br />

to u, then v, and then apply<strong>in</strong>g the composite function to w. Intuitively it’s say<strong>in</strong>g the same as:<br />

u(v(w)) == (u compose v)(w)<br />

We might state this law simply as: “function composition <strong>in</strong> an applicative functor works <strong>in</strong> the<br />

obvious way.”<br />

Applicative normal form<br />

The applicative laws taken together can be seen as say<strong>in</strong>g that we can rewrite any expression<br />

<strong>in</strong>volv<strong>in</strong>g unit or apply (and therefore by extension map2), <strong>in</strong>to a normal form hav<strong>in</strong>g one of the<br />

follow<strong>in</strong>g shapes:<br />

pure(x)<br />

// for some x<br />

map(x)(f) // for some x and f<br />

map2(x, y)(f) // for some x, y, and f<br />

map3(x, y, z)(f) // for some x, y, z, and f<br />

// etc.<br />

Where f, x, y, and z do not <strong>in</strong>volve the Applicative primitives at all. That is, every expression <strong>in</strong> an<br />

applicative functor A can be seen as lift<strong>in</strong>g some pure function f over a number of arguments <strong>in</strong> A.<br />

Note that this reason<strong>in</strong>g is lost when the applicative happens to be a monad and the expressions<br />

<strong>in</strong>volve flatMap. The applicative laws amount to say<strong>in</strong>g that the arguments to map, map2, map3, etc<br />

can be reasoned about <strong>in</strong>dependently, and an expression like flatMap(x)(f) explicitly <strong>in</strong>troduces a<br />

dependency (so that the result of f depends on x). See the note above on “The cost of power”.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!