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 30<br />

That is, if we have a value x of type F[F[F[A]]], we can jo<strong>in</strong> twice to get F[A], or we can map jo<strong>in</strong><br />

over the outer F and then jo<strong>in</strong> the result of that.<br />

This is say<strong>in</strong>g that <strong>in</strong> “flatten<strong>in</strong>g” F[F[F[A]]] to F[A], it should not matter whether we first jo<strong>in</strong> the<br />

two “<strong>in</strong>ner” Fs or the two “outer” Fs. This is easy to see with the List monad. If we have a List of<br />

Lists of Lists, like this…<br />

val x: List[List[List[Int]]] =<br />

List(List(List(1,2), List(3,4)), List(List(5,6), List(7,8)))<br />

…it should not matter whether we flatten the <strong>in</strong>ner lists or the outer lists first:<br />

scala> val y1 = x.flatten<br />

y1: List[List[Int]] = List(List(1, 2), List(3, 4), List(5, 6), List(7, 8))<br />

scala> val y2 = x.map(_.flatten)<br />

y2: List[List[Int]] = List(List(1, 2, 3, 4), List(5, 6, 7, 8))<br />

scala> y1.flatten<br />

res0: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)<br />

scala> y2.flatten<br />

res1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)<br />

This is the same as say<strong>in</strong>g that <strong>in</strong> the expression ((1 + 2) + (3 + 4)) + ((5 + 6) + (7 + 8)), it<br />

doesn’t matter whether we remove the <strong>in</strong>ner brackets first to get (1 + 2 + 3 + 4) + (5 + 6 + 7<br />

+ 8) or the outer brackets first to get (1 + 2) + (3 + 4) + (5 + 6) + (7 + 8). In both cases we<br />

end up with 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8. The reason it doesn’t matter is that + is associative.<br />

So then it’s easy to see how the monad law is an associative law.<br />

The identity laws <strong>in</strong> terms of jo<strong>in</strong> are similarly simple:<br />

jo<strong>in</strong>(unit(x)) == x<br />

// left identity<br />

jo<strong>in</strong>(map(x)(unit)) == x // right identity<br />

In terms of the list monad as above, the identity laws are say<strong>in</strong>g that we can add brackets either on<br />

the <strong>in</strong>side or the outside. Whichever we do, jo<strong>in</strong> will behave the same way:

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

Saved successfully!

Ooh no, something went wrong!