05.03.2016 Views

Programming in Scala”

fpiscompanion

fpiscompanion

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter notes 34<br />

def map[R,A,B](f: A => B): Reader[R, A] => Reader[R, B] =<br />

Reader(r => f compose r.run)<br />

The mean<strong>in</strong>g of jo<strong>in</strong> is to pass the same argument as both parameters to a b<strong>in</strong>ary function:<br />

def jo<strong>in</strong>[R,A](x: Reader[R, Reader[R, A]]): Reader[R, A] =<br />

Reader(r => x.run(r).run(r))<br />

And the mean<strong>in</strong>g of unit is to ignore the argument:<br />

def unit[R,A](a: A): Reader[R, A] = Reader(_ => a)<br />

The reader monad subsumes (and is simpler than) dependency <strong>in</strong>jection¹⁴⁴. See Rúnar’s talks on<br />

dependency <strong>in</strong>jection with the reader monad:<br />

“Dead-simple dependency <strong>in</strong>ection”, from the 2012 Northeast Scala Symposium <strong>in</strong> Boston¹⁴⁵<br />

“Lambda: the ultimate dependency <strong>in</strong>jection framework”, from the 2012 YOW! Summer Conference<br />

<strong>in</strong> Brisbane¹⁴⁶<br />

See also Tony Morris’s talk “Dependency <strong>in</strong>jection without the gymnastics”¹⁴⁷ from ETE 2012.<br />

Eilenberg-Moore categories<br />

Another categorical view of monads is through Eilenberg-Moore categories¹⁴⁸. The EM category of<br />

a monad is the category of its algebras¹⁴⁹.<br />

For example, the algebras for the List monad are Scala Monoids. The EM category of the List monad<br />

is the category with monoids as its objects and monoid morphisms¹⁵⁰ (see chapter 10) as its arrows.<br />

In general, the EM category for a monad can be found by the follow<strong>in</strong>g method (source: Theory<br />

Lunch¹⁵¹):<br />

1. An F-algebra for the monad F is a type A together with a function a: F[A] => A such that<br />

a(unit(x)) == x and a(jo<strong>in</strong>(x)) == a(map(x)(a)).<br />

2. A morphism of F-algebras from an F-algebra a: F[A] => A to an F-algebra b: F[B] => B is<br />

a function f: A => B such that b(map(x)(f)) == f(a(x)).<br />

¹⁴⁴http://en.wikipedia.org/wiki/Dependency_<strong>in</strong>jection<br />

¹⁴⁵https://www.youtube.com/watch?v=ZasXwtTRkio<br />

¹⁴⁶http://yow.eventer.com/yow-2012-1012/lambda-the-ultimate-dependency-<strong>in</strong>jection-framework-by-runar-bjarnason-1277<br />

¹⁴⁷http://vimeo.com/44502327<br />

¹⁴⁸http://ncatlab.org/nlab/show/Eilenberg-Moore+category<br />

¹⁴⁹https://www.fpcomplete.com/user/bartosz/understand<strong>in</strong>g-algebras<br />

¹⁵⁰http://en.wikipedia.org/wiki/Monoid#Monoid_homomorphisms<br />

¹⁵¹http://theorylunch.wordpress.com/2013/06/06/an-<strong>in</strong>itial-solution-to-the-monad-problem-and-then-some-more/#more-885

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

Saved successfully!

Ooh no, something went wrong!