Source

typeclassopedia.bitbucket.org / index.html

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js ie6" lang="en"> <![endif]-->
<!--[if IE 7]>    <html class="no-js ie7" lang="en"> <![endif]-->
<!--[if IE 8]>    <html class="no-js ie8" lang="en"> <![endif]-->
<!--[if gt IE 8]><!-->  <html class="no-js" lang="en"> <!--<![endif]-->
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

	<title>The Typeclassopedia</title>

	<meta name="description" content="The Typeclassopedia">
	<meta name="viewport" content="width=1024, user-scalable=no">

    <!-- fonts -->
    <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic,700italic|PT+Sans+Narrow:400,700|Ubuntu+Mono:400,700' type='text/css'>

	<!-- deck.js -->
	<link rel="stylesheet" href="core/deck.core.css">
	<link rel="stylesheet" href="extensions/goto/deck.goto.css">
	<link rel="stylesheet" href="extensions/menu/deck.menu.css">
	<link rel="stylesheet" href="extensions/status/deck.status.css">
	<link rel="stylesheet" href="extensions/hash/deck.hash.css">
	<link rel="stylesheet" id="transition-theme-link" href="themes/transition/fade.css">
	<link rel="stylesheet" id="style-theme-link" href="atlassian.css">
	<script src="jquery-1.7.min.js"></script>
	<script src="modernizr.custom.js"></script>
	<script src="core/deck.core.js"></script>
	<script src="extensions/hash/deck.hash.js"></script>
	<script src="extensions/menu/deck.menu.js"></script>
	<script src="extensions/goto/deck.goto.js"></script>
	<script src="extensions/status/deck.status.js"></script>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-41301772-1', 'bitbucket.org');
  ga('send', 'pageview');

</script>	

	<!-- highlight.js -->
	<link rel="stylesheet" href="solarized_light.css">
	<script src="highlight.pack.js"></script>

	<script>
	$(document).ready(function() {
		$.deck('.slide');
		$('pre').each(function(i, e) {
			hljs.highlightBlock(e, '  ');
		});
		$('code').each(function(i, e) {
			hljs.highlightBlock(e);
		});
	});
	</script>

</head>

<body class="deck-container">

<p class="deck-status">slide <span class="deck-status-current"></span> / <span class="deck-status-total"></span></p>

<form action="." method="get" class="goto-form">
	<label for="goto-slide">Go to slide:</label>
	<input type="text" name="slidenum" id="goto-slide" list="goto-datalist">
	<datalist id="goto-datalist"></datalist>
	<input type="submit" value="Go">
</form>

<section class="slide" style="font-size: 100%">
	<h1>
    <div>The Typeclassopedia</div>
  	<div style="font-size: 50%">John Kodumal, Atlassian</div>
  	<div style="font-size: 50%">jkodumal@atlassian</div>
	<div style="font-size: 50%"><br/></div>
	<div style="font-size: 25%">Use left and right arrows to navigate.</div>
	<div style="font-size: 25%">Japanese translation by Shingo Omura is <a href="index-ja.html">here<a>.</div>
  </h1>
</section>


<section class="slide">
	<h2>Typeclasses: Open-world interfaces</h2>
	<div class="slide">
		<p>Typeclasses are akin to Java interfaces, but more flexible.</p>
	</div>
	<div class="slide">
		<p>We declare them in scala with traits:</p>
<pre class="scala">
trait Show[A] {
	def shows(a: A): String
}
</pre>	
		<p>Note the subtle difference compared to the mix-in "interface" style:
<pre class="scala">
trait Show {
	def shows(): String
}	
</pre>
	</div>		
	<div class="slide">
		<p>We also need a way to add a type to the class:</p>
<pre class="scala">
implicit val IntShow = new Show[Int] {
	def shows(a: Int) = a.toString
}
</pre>
</section>

<section class="slide">
	<h2>Using a typeclass</h2>
	<div class="slide">
		<p>We use scala implicits:</p>
<pre>
def shows[A](a : A)(implicit shower: Show[A]) = shower.shows(a)
</pre>
	</div>
	<div class="slide">
		<p>Or alternatively, using <em>context bounds</em>:</p>
<pre class="scala">
def shows[A : Show](a : A) = implicitly[Show[A]].shows(a)
</pre>
		<p>(implicitly is part of predef: <code>def implicitly[A](implicit a : A) = a</code>)</p>
	</div>
	<div class="slide">
		<p>Scalaz pimps a set of common typeclasses for us, so we can just do:</p>
<pre class="scala">
3.shows // must have a "Show[Int]" instance in scope, or will fail to type check
</pre>
	</div>	
</section>

<section class="slide">
	<h2>The Open-World Assumption</h2>
	<p>What have we gained?</p>
	<ul>
		<div class="slide">
			<li>We can declare instances <em>outside</em> of the types themselves</li>
			<ul>
				<li> <code>Int</code> knows nothing about <code>Show</code>
			</ul>
		</div>
		<li class="slide">This is the <em>open world assumption</em></li>
		<div class="slide">
			<li>In Scala, we can <em>override</em> the typeclass instance by putting a new one in scope:
<pre class="scala">
def unaryShows(x : Int) : String = { 
	implicit val AltIntShow = new Show[Int] {
		def shows(i : Int) = (1 to i) map(_ => "|") mkString
	}
	shows(x)
}
println shows(5)      // prints '5'
println unaryShows(5) // prints '|||||'	
</pre>
		</div>
	</ul>
</section>

<section class="slide">
	<h2>Typeclasses <code>/==</code> Subtype polymorphism</h2>
	<p>What we <em>can't</em> do with Scala's typeclasses (<a href="https://gist.github.com/2026129">not easily at least</a>):
<pre class="java">
interface Show {
	String show();
}

class Foo extends Show {
	public String show() {
		return "a foo";
	}
}

class Bar extends Show {
	public String show() {
		return "a bar";
	}
}

List[Show] showList = new ArrayList(new Foo(), new Bar(), new Foo());

for (String s : showList) {
	System.out.println(s.show);
}
</pre> 
</section>

<section class="slide">
	<h2>The Typeclassopedia</h2>
	<img src="images/typeclassopedia.png" style="float: right; width: 100%; margin-left: 20px;">
	<p>A set of interrelated typeclasses that have proven handy for structuring functional code:
	<ul>
		<li class="slide"><em>Functional design patterns</em></li>
		<li class="slide">There's mostly* nothing magical about these typeclasses</li>
		<li class="slide">In scala, they're provided by a library called scalaz (pronounced scala-zed)</li>
		<li class="slide">These examples are based on <a href="https://github.com/scalaz/scalaz/">scalaz 7.0.0</a></li>
		<li class="slide">This is how the hierarchy is defined in Haskell--- it isn't perfect</li>
	</ul>
	<p class="slide">We'll cover functors, applicative functors, monad, monad transformers, and traversable</p>
	<p class="slide" style="font-size: 60%">*one exception: <code>for</code> comprehensions and monads</p>
</section>

<section class="slide">
	<h2>Introducing Functor</h2>
	<div class="slide">
	<p>A functor is simply something you can map over. It defines a single method:</p>
<pre class="scala">
trait Functor[F[_]] {
	def map[A,B](fa: F[A])(f: A => B) : F[B]
}
</pre>
	</div>
	<div class="slide">
		<p>An instance for <code>Option</code>:</p>
<pre class="scala">
implicit val OptionFunctor = new Functor[Option] {
	def map[A, B](fa: Option[A])(f: A => B) : Option[B] = 
		fa match {
			case Some(a) => Some(f(a))
			case None => None
		}
}
</pre>
	</div>
	<div class="slide">
		<p>In Haskell, the arguments are reversed:</p>
<pre class="haskell">
class Functor f where  
    fmap :: (a -> b) -> f a -> f b	
</pre>
	</div>
	<div class="slide">
		<p>In the Haskell version, we see how <code>f</code> is <em>lifted</em> into the functor context.</p>
	</div>
</section>

<section class="slide">
	<h2>Fun with Functions as Functors</h2>
	<p>"Thing you can map over" leads to obvious examples:</p>
	<ul>
		<li class="slide">Lists</li>
		<li class="slide">Trees</li>
		<li class="slide">Maps</li>
	</ul>
	<div class="slide">
		<p>Let's look at something less obvious: Functions!</p>
<pre>
implicit def FunctionFunctor[R] = new Functor[({type l[a] = R=>a})#l] {
	def map[A, B](fa: R => A)(f: A => B) : R => B = (x => f(fa(x)))
}
</pre>
	</div>
	<h6 class="slide">Pop quiz: I defined map in a slightly funky way. What simple concept is this expressing?</h6>
	<div class="slide">
		<p>Again, the Haskell version makes this much clearer. Start with <code>fmap</code>:</p>
<pre class="haskell">
    fmap :: (a -> b) -> f a -> f b	
</pre>
	</div>
	<div class="slide">
		<p>Substitute <code>r -> a</code> for <code>f a</code></p>
<pre class="haskell">
    fmap :: (a -> b) -> (r -> a) -> (r -> b)	
</pre>
	</div>
	<p class="slide">Aside: This is where the "box" analogy starts falling apart, and we start throwing around vague terms like "computational context"...</p>
</section>

<section class="slide">
	<h2>Functor Laws</h2>
	<p>There are some additional constraints on Functors that make them "behave appropriately":</p>
	<ul>
		<div class="slide">
			<li><code>map(fa)(id) === fa</code></li> (Mapping over the identity function produces the original functor)
		</div>
		<div class="slide">	
			<li><code>map(fa)(f compose g) === map(map(fa)(g))(f)</code></li> (Mapping over a composed function is the same as mapping over each function)
		</div>
	</ul>
	<p class="slide">These laws prevent ridiculous definitions of <code>map</code>, and make it possible to predict how functions behave.</p>
	<p class="slide">Note that these laws are <strong>not</strong> enforced by the type system.
</section>

<section class="slide">
	<h2>Aside: Parametricity</h2>
	<blockquote class="slide">
		<p>With great weakness comes great power...</p>
		<cite>Ben "Pierce" Parker</cite>
	</blockquote>
	<blockquote class="slide">
		<p>Mo' power, mo' problems...</p>
		<cite>Biggie Smalls</cite>
	</blockquote>
	<div class="slide">
<pre class="scala">
def fun[A](a : A) : A = ...
</pre>
	<p>What is <code>fun</code>?</p>
	</div>
	<div class="slide">
<pre class="scala">
val x : List[Int] = ...
def foo[F[_] : Functor](fs : F[Int]) = ...
</pre>
	<p>What is <code>foo(x).length?</code><p>
	</div>
</section>

<section class="slide">
	<h2>Introducing Applicative Functor</h2>
	<p>You can get pretty far on <code>map</code> alone... but sometimes you need more.</p>
	<div class="slide">
		<p>Consider the following:</p>
<pre class="scala">
def parse(s : String) : Option[Int] = ...
</pre>
	</div>
	<div class="slide">
		<p>Let's try to add two parsed integers with <code>map</code>:</p>
<pre class="scala">
parse("3").map((x: Int) => (y: Int) =>  x + y) // ???
</pre>
	</div>
	<div class="slide">
		<p>We're left with an <code>Option[Int => Int]</code>... but what can we do with that?
	</div>
	<h5 class="slide">We'll need a more powerful <code>map</code>-like operation</h5>
</section>

<section class="slide">
	<h2>Applicative Functors</h2>
	<div class="slide">
		<p>Let's add the power we need to <code>Functor</code>:
<pre class="scala">
trait Applicative[F[_]] extends Functor {
	def <*>[A, B](fa: F[A])(f : F[A => B]) : F[B]
	// ... there's more to Applicative, to be shown shortly
}
</pre>
	</div>
	<div class="slide">
		<p>Which makes our previous example look something like:</p>
<pre class="scala">
(parse("3")).<*>(parse("Nope").map(x => (y : Int) => x + y))
</pre>
		<p style="font-size: 60%">(Yuck)</p>
	</div>
</section>

<section class="slide">
	<h2>Applicative Syntax</h2>
	<div>
		<p>In Haskell, things look a little more obvious: </p>
<pre class="haskell">
(+) <$> parse("3") <*> parse("Nope") 
</pre>	
	</div>
	<div class="slide">
		<p>Generalizing a bit, we go from calling a pure function: </p>
<pre class="haskell">
f x y z
</pre>
	</div>
	<div class="slide">
		<p>To calling a function on "effectful" arguments: </p>
<pre class="haskell">
f <$> x <*> y <*> z
</pre>
	</div>
	<div class="slide">
		<p>Scalaz's <code>ApplicativeBuilder</code> improves the situation somewhat:</p>
<pre class="scala">
(parse("3") |@| parse("Nope"))(_ + _)
</pre>
	</div>	
</section>

<section class="slide">
	<p style="font-size: 2500%">|@|</p>
</section>

<section class="slide">
	<img src="images/macaulay.jpg" style="float: right; width: 100%;">
	<h3>(The Macaulay Culkin Function)</h3>
</section>

<section class="slide">
	<h2>More on Applicatives</h2>
	<div class="slide">
		<p>What if some of the arguments aren't <code>Option</code>?
<pre class="scala">
	(parse("3") |@| 4 /* uh oh, no macaulay for my culkin */) (_ + _)
</pre>
	</div>	
	<div class="slide">
		<p>One small addition to our type class:</p>
<pre class="scala">
trait Applicative[F[_]] extends Functor {
	def <*>[A, B](fa: F[A])(f : F[A => B]) : F[B]
	<strong>def point[A](a : A): F[A]</strong>
}
</pre>
	<h6 class="slide">Exercise: Define the applicative instance for <code>Option</code></h6>
	</div>
	<div class="slide">
	<p>With <code>point</code>, we can express the above example as:</p>
<pre class="scala">
	(parse("3") |@| 4.point[Option]) (_ + _)
</pre>
	</div>
</section>

<!--
<section class="slide">
	<p style="font-size: 2250%"><|*|></p>
</section>

<section class="slide">
	<img src="images/mr-incredible.jpg" style="float: right; width: 100%;">
	<h3>(Asterisks Man, Arms Akimbo)</h3>
</section>
-->

<section class="slide">
	<h2>A Tutorial on Monads</h2>
	<div class="slide">
		<img src="images/ackbar.jpeg" style="width=100%">
	</div>
	<div class="slide">
		<a href="http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/"><h4>Yes, it's a trap</h4></a>
	</div>
</section>

<section class="slide">
	<h2>Introducing Monads</h2>
	<p>As before, we'll introduce a new task and see what goes wrong...</p>
	<div class="slide">
		<p>Take our <code>parse</code> example again:</p>
<pre class="scala">
def parse(s : String) : Option[Int] = ...
</pre>
	</div>
	<div class="slide">
		<p>What if our input <code>String</code> was an optional query parameter?
<pre class="scala">
val x : Option[String] = params.get("x")
</pre>
		<p>We've got an <code>Option[String]</code> and a function <code>String => Option[Int]</code></p>
	</div>
	<div class="slide">
		<p>When all you have is a <code>map</code> hammer...</p>
<pre class="scala">
x.map(parse) // Option[Option[Int]] ??
</pre>
	</div>	
</section>

<section class="slide">
	<h2>Monads</h2>
	<div class="slide">
		<p>Let's add the power we need to <code>Applicative</code>:
<pre class="scala">
trait Monad[F[_]] extends Applicative {
	def >>=[A, B](fa: F[A])(f : A => F[B]) : F[B]
}
</pre>
	<p>This is pronounced <code>bind</code></p>
	</div>
	<div class="slide">
		<p>It makes our previous example look something like:</p>
<pre class="scala">
params.get("x") >>= parse // Option[Int]
</pre>
	</div>
	<div class="slide">
		<p>A more complete web-based calculator example:</p>
<pre class="scala">
params.get("x") >>= parse >>= (x => (params.get("y") >>= parse) map (_ + x) )
</pre>
<p style="font-size: 60%">(Yuck)</p>
	</div>
</section>

<section class="slide">
	<h2>Syntactic Sugar to the Rescue</h2>
	<div class="slide">
		<p>The last example hints at a fairly typical pattern: </p>
<pre class="scala">
monadicX >>= (x => monadicY >>= (y => monadicZ map (z => x+y+z))) 
</pre>
		<p>We have nested <code>bind</code>'s with a final <code>map</code></p>
	</div>
	<div class="slide">
		<p>Reformatting it a bit: </p>
<pre class="scala">
monadicX >>= (x => 
monadicY >>= (y => 
monadicZ map (z => 
   x+y+z
))) 
</pre>
	</div>
	<div class="slide">
		<p>With Scala <code>for</code> comprehensions, this becomes:
<pre class="scala">
for {
	x <- monadicX
	y <- monadicY
	z <- monadicZ
} yield x + y + z
</pre>
	<p style="font-size:60%">(Much nicer!)</p>
	</div>

</section>

<section class="slide">
	<h2>A Monad Hidden in Plain Sight</h2>
	<div class="slide">
	<p>Let's move beyond the <code>Option</code> example. Recall that there is a functor instance for functions:</p>
	<pre>
def map[A, B](fa: R => A)(f: A => B) : R => B = (x => f(fa(x)))
	</pre>
	</div>
	<div class="slide">
		<p>What about a monad instance?</p>	
		<pre>
implicit def FunctionMonad[R] = new Monad[({type l[a] = R=>a})#l] {
	def flatMap[A, B](fa: R => A)(f: A => R => B) : R => B = (x => f(fa(x))(x))
	...
}
		</pre>
	</div>
	<div class="slide">
		<p>This is commonly referred to as the <code>Reader</code> monad. It looks a bit inscrutable, so let's see where it may come in handy.</p>
	</div>	
</section>

<section class="slide">
	<h2>Motivating the Reader Monad</h2>
	<div class="slide">
		<p>Let's say we need to build absolute URLs for a web app, and the app has a base URL:</p>
<pre class="scala">
def makeAbs(base: AbsURL, url: URL): AbsURL = AbsURL(base + url)
</pre>
	</div>
	<div class="slide">
		<p>But this leads to a lot of repetition:</p>
<pre class="scala">
val links = Map("self" -> makeAbs(<strong>baseURL</strong>, "/widgets/523"),
                "parent" -> makeAbs(<strong>baseURL</strong>, "/widgets") )
</pre>
	</div>
	<div class="slide">
		<p>Let's redefine <code>makeAbsolute</code> with <code>Reader</code>:</p>
<pre class="scala">
def makeAbs(url: URL): Reader[AbsURL, AbsURL] = 
	Reader(base => AbsURL(base + url))
</pre>
	</div>

	<div class="slide">
		<p>All we've done is a syntactic switcharoo, but this lets us write:</p>
<pre class="scala">
(for {
	self   <- makeAbs("/widgets/523")
	parent <- makeAbs("/widgets")
} yield Map("self" -> self, "parent" -> parent))(baseURL)
</pre>
	<p>Think of <code>Reader</code> as a computation with a <em>read-only environment</em> (the argument) that can be supplied to produce a result.</p>
	</div>
</section>


<section class="slide">
	<h2>Monad as Embedded Language</h2>
	<div class="slide">
		<p>Here's a <a href="http://en.wikibooks.org/wiki/Haskell/Understanding_monads">stab</a> at providing an intuition for monads. Consider:</p>
<pre class="scala">
for {
	x <- monadicX
	y <- monadicY
} yield x + y
</pre>
		<p>Q: What does this code do?</p>
	</div>
	<div class="slide">
		<p>A: Depends on the monad.</p>
	</div>
	<div class="slide">
		<p>A monadic <code>for</code> comprehension is an embedded programming language with semantics defined by the monad:</p>
	</div>
	<div class="slide">
		<table style="width: 100%">
			<tr>
				<th align="left">Monad</th>
				<th align="left">Semantics</th>
			</tr>
			<tr class="slide">
				<td><code>Option</code></td>
				<td>Anonymous exceptions</td>
			</tr>
			<tr class="slide">
				<td><code>Reader</code></td>
				<td>Read-only environment</td>
			</tr>
			<tr class="slide">
				<td><code>Validation</code></td>
				<td>Descriptive exceptions</td>
			</tr>
			<tr class="slide">
				<td><code>List</code></td>
				<td>Nondeterministic computation</td>
			</tr>
		</table>
	</div>
</section>

<section class="slide">
	<h2>Languages with Multiple Effects</h2>
	<p>In the real world, we have to deal with multiple monads (effects):</p>
	<ul>
		<li class="slide">A data store takes a DB configuration (<code>Reader</code>), and the connection may fail (<code>Validation</code>)</li>
		<li class="slide">A computation may be asynchronous (<code>Future</code>), and may produce multiple results (<code>List</code>)</li>
		<li class="slide">A remote call may fail if the service is down (<code>Validation</code>), and we want to log responses (<code>Writer</code>)</li>
	</ul>
	<div class="slide">
	<p>Let's see why working with stacked monads gets ugly. We'll add a read-only environment to our calculator:</p>
<pre class="scala">
type Env = Map[String, Int]
def lookup(s: String): Reader[Env, Option[Int]] = 
	Reader(env => env.get(s) orElse parse(s))
</pre>
	</div>
	<div class="slide">
		<p>Now we'll add two numbers, using <code>Reader</code> to avoid repeating the <code>env</code> argument:</p>		
<pre class="scala">
for {
 xOpt <- lookup("3")
 yOpt <- lookup("y")
} yield (for {
          x <- xOpt
          y <- yOpt
         } yield x + y)
</pre>
	<p style="font-size: 60%">(Yuck)</p>
	</div>
</section>

<section class="slide">
	<img src="images/turtle.jpg" style="float: right; width: 100%;">
	<h3>...all the way down</h3>
</section>

<section class="slide">
	<h2>They see me composin'... they hatin'</h2>
	<p>Life would be easier if monads <em>composed</em>. Given monads <code>M[_]</code> and <code>N[_]</code>, is <code>M[N[_]]</code> a monad? </p>
	<div class="slide">
		<p>We can work this out for functors:</p>
<pre class="scala">
implicit val ComposedFunctor[M: Functor, N: Functor] = new Functor[...] {
	def map[A, B](fa: M[N[A]])(f: A => B) : M[N[B]] = fa.map(_.map(f(_)))
}
</pre>
	</div>
	<div class="slide">
		<p>It's ironic (like rain on your wedding day), but in general, monads don't compose. Try it:
<pre class="scala">
implicit val ComposedMonad[M: Monad, N: Monad] = new Monad[...] {
	def >>=[A, B](fa: M[N[A]])(f: A => M[N[B]]) : M[N[B]] = // ???
}
</pre>
	</div>
</section>

<section class="slide">
	<h2>Monad Transformers</h2>
	<div class="slide">
		<p><em>Monad transformers</em> represent one solution. A transformer is a "wrapper" around a monadic value:</p>
<pre class="scala">
case class OptionT[F[+_], +A](run: F[Option[A]]) { 
	// More to be shown shortly 
}
</pre>
	</div>
	<div class="slide">
		<p>The wrapped value will expose the underlying monad's utility functions:</p>
<pre code="scala">
OptionT(List(Some(3), None, Some(4))).getOrElse(0) // List(3, 0, 4)
</pre>
	</div>
	<div class="slide">
		<p>Most importantly, we'll make the transformer itself a monad:</p>
<pre class="scala">
case class OptionT[F[+_], +A](run: F[Option[A]]) { 
	def >>=[B](f: A => OptionT[F, B])(implicit F: Monad[F]): OptionT[F, B] = 
		new OptionT[F, B](
			self.run >>= (a => a.match {
								case None => F.point(None)
								case Some(s) => f(s).run
							}))  
	...
}
</pre>
		<p>We can stack transformers arbitrarily deep!</p>
	</div>
</section>

<section class="slide">
	<h2>De-turtling our previous example</h2>
	<div class="slide">
		<p>scalaz defines transformers for most common monads:</p> 
		<ul>
			<li><code>OptionT</code>
			<li><code>ListT</code>
			<li><code>EitherT</code>
			<li><code>ReaderT</code>, aka <code>Kleisli</code>
		</ul>		
	</div>
	<div class="slide">
		<p>Let's clean up our previous example with <code>ReaderT</code>. Recall we had:
<pre class="scala">
for {
 xOpt <- lookup("3") 
 yOpt <- lookup("y") 
} yield (for {
          x <- xOpt
          y <- yOpt
         } yield x + y)
</pre>			
	</div>
	<div class="slide">
		<p>With <code>ReaderT</code>:
<pre class="scala">
for {
	x <- Kleisli(lookup("3"))
	y <- Kleisli(lookup("y"))
} yield x + y
</pre>
	<p style="font-size:60%">(Much nicer!)</p>
	</div>
</section>

<section class="slide">
	<h2>The Monad Transformer Typeclass</h2>
	<div class="slide">
		<p>There is a typeclass for monad transformers, which defines a single operation <code>liftM</code>:</p>
<pre class="scala">
trait MonadTrans[F[_[_], _]] {
  def liftM[G[_] : Monad, A](a: G[A]): F[G, A]
}
</pre>
	</div>
	<div class="slide">
		<p><code>liftM</code> gives us the ability to "lift" computations in the base monad into the transformed monad:</p>
<pre class="scala">
(for {
	x <- OptionT(List(Some(3), None))
	y <- List(1,2).liftM[OptionT]
} yield x + y).run // List(Some(4), None, Some(5), None)
</pre>
	</div>
</section>

<section class="slide">
	<h2>Another take on composing monads</h2>
	<div class="slide">
		<p>An alternative formulation of <code>Monad</code> provides some insight into the composition problem. Instead of <code>bind</code>, it's sufficient to implement <code>join</code>:<p>
		<pre class="scala">
trait Monad[F[_]] extends Applicative {
	def join[A](fa: F[F[A]]): F[A]
}
		</pre>
	</div>
	<h6 class="slide">Exercise: Define <code> >>= </code> using <code>join</code> and <code>map</code></h6>
	<div class="slide">
		<p>Using <code>join</code>, let's try to make a monad for <code>M[N[_]]</code>. Substituting <code>M[N[_]]</code> for <code>F[_]</code>, we get:</p>
<pre class="scala">
def join[A](fa: M[N[M[N[A]]]]]): M[N[A]]
</pre>
		<p style="font-size: 60%">(Whew!)</p>			
	</div>
	<div class="slide">
		<p>The <code>join</code> methods defined on <code>M</code> and <code>N</code> don't help, because they're "blocked" by the other monad. But what if we could "commute" the monads, or change the sequence of the <code>M</code>'s and <code>N</code>'s?
<pre class="scala">
def sequence[A](a: M[N[A]]): N[M[A]]
</pre>
	</div>
	<div class="slide">
		<p>This works! It's possible to define monad composition given the <code>sequence</code> function.</p>
	</div>
</section>

<section class="slide">
	<h2>Introducing Traverse</h2>
	<div class="slide">
	<p>The <code>Traverse</code> typeclass provides exactly this. It gives the ability to commute two functors:</p>
	<pre class="scala">
trait Traverse[F[_]] extends Functor {
	def sequence[G[_]: Applicative, A](fga: F[G[A]]): G[F[A]]
}
	</pre>	
			<p style="font-size: 60%">(scalaz uses an alternative formulation based on a function <code>traverse: F[A] => (A => G[B]) => G[F[B]]</code>)</p>	
	</div>
	<div class="slide">
		<p><code>Traverse</code> is tremendously handy in its own right. For example, let's turn a list of asynchronous computations into an asynchronous computation of a list:</p>
<pre class="scala">
List(future { doCalc1() }, future { doCalc2() }).sequence // Future[List[Int]]
</pre>
	</div>
</section>

<section class="slide">
	<h2>Monad composition for free</h2>
	<div class="slide">
		<p>Assuming we also have a <code>Traverse</code> requirement on monad <code>N</code>, we can get a composed monad for "free": </p>
<pre class="scala">
implicit val ComposedMonad[M: Monad, N: Monad: Traverse] = new Monad[...] {
	def >>=[A, B](fa: M[N[A]])(f: A => M[N[B]]) : M[N[B]] = // ???
}	
</pre>
		<h6 class="slide">Exercise: Implement <code> >>= </code> for <code>ComposedMonad</code>.</h6>
	</div>
	<div class="slide">
		<p>This could be used to supply monad transformer implementations, though the "free" transformer doesn't always give the semantics we want. Note that scalaz doesn't use this "free" formulation.
	</div>

</section>

</body>
</html>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.