-
Notifications
You must be signed in to change notification settings - Fork 2
/
scalamatsuri.txt
288 lines (212 loc) · 6.72 KB
/
scalamatsuri.txt
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
| \gReducing Boilerplate and Combining Effects:
| \gA Monad Transformer Example
| Scala Matsuri - Feb 25th, 2017
| Connie Chen - \b@coni
/
ボイラープレートの削減と作用の組み合わせ: 例で見るモナド変換子
---
| \gHello
* @coni
* Data Platform team @ Twilio
@ http://github.com/conniec
---
| \gWhat are Monad transformers?
* Monad transformers allow different monads to compose
* Combine effects of monads to great a \bSUPER MONAD
* Eg. Future[Option], Future[Either], ReaderT[Option]
* In this example, we will use the Cats library...
/
モナド変換子は異なるモナドの合成を可能とする
---
\g Future[Either[A, B]] turns into EitherT[Future, A, B]
\g Future[Option[A]] turns into OptionT[Future, A]
---
\g Example: Making coffee!
--
\b Step 1. Grind the beans
ステップ 1. コーヒー豆を挽く
--
```
import scala.concurrent.Future
import cats.data.OptionT
import cats.implicits._
import scala.concurrent.ExecutionContext.Implicits.global
case class Beans(fresh: Boolean = true)
case class Grounds()
class GroundBeansException(s: String) extends Exception(s: String)
```
--
```
def grindFreshBeans(beans: Beans, clumsy: Boolean = false): Future[Option[Grounds]] = {
if (clumsy) {
Future.failed(new GroundBeansException("We are bad at grinding"))
} else if (beans.fresh) {
Future.successful(Option(Grounds()))
} else {
Future.successful(None)
}
}
```
--
Three different kind of results
* Value found
* Value not found
* Future failed
/
値が見つかる、値が見つからない、Futureの失敗という 3種類の結果
---
\b Step 2. Boil hot water
ステップ 2. お湯を沸かす
--
```
case class Kettle(filled: Boolean = true)
case class Water()
case class Coffee(delicious: Boolean)
class HotWaterException(s: String) extends Exception(s: String)
--
def getHotWater(kettle: Kettle, clumsy: Boolean = false): Future[Option[Water]] = {
if (clumsy) {
Future.failed(new HotWaterException("Ouch spilled that water!"))
} else if (kettle.filled) {
Future.successful(Option(Water()))
} else {
Future.successful(None)
}
}
```
---
\b Step 3. Combine water and coffee (it's a pourover)
ステップ 2. お湯とコーヒー豆を組み合わせる (ハンドドリップです)
--
```
def makingCoffee(grounds: Grounds, water: Water): Future[Coffee] = {
println(s"Making coffee with... $grounds and $water")
Future.successful(Coffee(delicious=true))
}
```
---
\g Without Monad transformers, success scenario
```
// Step 1. def grindFreshBeans(beans: Beans, clumsy: Boolean = false): Future[Option[Grounds]]
// Step 2. def getHotWater(kettle: Kettle, clumsy: Boolean = false): Future[Option[Water]]
// Step 3. def makingCoffee(grounds: Grounds, water: Water): Future[Coffee]
val coffeeFut = for {
beans <- grindFreshBeans(Beans(fresh=true))
hotWater <- getHotWater(Kettle(filled=true))
beansResult = beans.getOrElse(throw new Exception("Beans result errored. "))
waterResult = hotWater.getOrElse(throw new Exception("Water result errored. "))
result <- makingCoffee(beansResult, waterResult)
} yield Option(result)
coffeeFut.onSuccess {
case Some(s) => println(s"SUCCESS: $s")
case None => println("No coffee found?")
}
coffeeFut.onFailure {
case x => println(s"FAIL: $x")
}
```
/
モナド変換子を使わない場合の成功シナリオ
---
\g With Monad transformers, success scenario
```
val coffeeFutMonadT = for {
beans <- OptionT(grindFreshBeans(Beans(fresh=true)))
hotWater <- OptionT(getHotWater(Kettle(filled=true)))
result <- OptionT.liftF(makingCoffee(beans, hotWater))
} yield result
coffeeFutMonadT.value.onSuccess {
case Some(s) => println(s"SUCCESS: $s")
case None => println("No coffee found?")
}
coffeeFutMonadT.value.onFailure {
case x => println(s"FAIL: $x")
}
```
/
モナド変換子を使った場合の成功シナリオ
---
\g Helper functions on OptionT
\b `fromOption` gives you an OptionT from Option
Internally, it is wrapping your option in a Future.successful()
\b `liftF` gives you an OptionT from Future
Internally, it is mapping on your Future and wrapping it in a Some()
/
OptionT のヘルパー関数
---
\g Without Monad transformers, failure scenario
```
val coffeeFut3 = for {
beans <- grindFreshBeans(Beans(fresh=false))
hotWater <- getHotWater(Kettle(filled=true))
beansResult = beans.getOrElse(throw new Exception("Beans result errored. "))
waterResult = hotWater.getOrElse(throw new Exception("Water result errored. "))
result <- makingCoffee(beansResult, waterResult)
} yield Option(result)
coffeeFut3.onSuccess {
case Some(s) => println(s"SUCCESS: $s")
case None => println("No coffee found?")
}
coffeeFut3.onFailure {
case x => println(s"FAIL: $x")
}
```
/
モナド変換子を使わない場合の失敗シナリオ
---
\g With Monad transformers, failure scenario
```
val coffeeFut2 = for {
beans <- OptionT(grindFreshBeans(Beans(fresh=false)))
hotWater <- OptionT(getHotWater(Kettle(filled=true)))
result <- OptionT.liftF(makingCoffee(beans, hotWater))
} yield result
coffeeFut2.value.onSuccess {
case Some(s) => println(s"SUCCESS: $s")
case None => println("No coffee found?")
}
coffeeFut2.value.onFailure {
case x => println(s"FAIL: $x")
}
```
/
モナド変換子を使った場合の失敗シナリオ
---
\g With Monad transformers, failure scenario with exception
```
val coffeeFut2 = for {
beans <- OptionT(grindFreshBeans(Beans(fresh=true)))
hotWater <- OptionT(getHotWater(Kettle(filled=true), clumsy=true))
result <- OptionT.liftF(makingCoffee(beans, hotWater))
} yield result
coffeeFut2.value.onSuccess {
case Some(s) => println(s"SUCCESS: $s")
case None => println("No coffee found?")
}
coffeeFut2.value.onFailure {
case x => println(s"FAIL: $x")
}
```
/
モナド変換子を使った場合の例外を投げる失敗シナリオ
---
\g What did we learn?
* Use monad transformers to short circut your chained monads
連鎖したモナドをショートさせるのにモナド変換子を使う
--
* Instead of unwrapping layers of monads, monad transformers results in a new monad to flatMap with
入れ子になったモナドを分解する代わりに、モナド変換子は flatMap 可能な新しいモナドを作る
--
* Reduce layers of x.map( y => y.map ( ... )) to just x.(map ( y => ...))
x.map ( y => y.map ( ... ) ) と入れ子になった呼び出しも一つの map で済むようになる
---
\g What's next?
* Many other types of monad transformers: ReaderT, WriterT, EitherT, StateT
* Since monad transformers give you a monad as a result-- you can stack them too!
/
OptionT 以外にも多くのモナド変換子がある。複数積み上げることも可能。
---
| \rThank you
| Connie Chen - \b@coni
| Twilio
| We're hiring!