-
Notifications
You must be signed in to change notification settings - Fork 0
/
fpinCh10.scala
461 lines (400 loc) · 11.4 KB
/
fpinCh10.scala
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
// Monoids!
object ch10 {
trait Monoid[T] {
def op(x1: T, x2: T): T
def zero: T
}
val stringMonoid = new Monoid[String] {
def op(x1: String, x2: String): String =
x1 + x2
val zero = ""
}
def listMonoid[T] = new Monoid[List[T]] {
def op(x1: List[T], x2: List[T]) = x1 ++ x2
val zero: List[T] = Nil
}
def testMonoid[T] (m: Monoid[T], opTests: ((T,T), T)*) {
def testOneExample(a: T, b: T, r: T) {
assert(m.op(a,b) == r)
assert(m.op(a, m.zero) == a)
assert(m.op(m.zero, a) == a)
assert(m.op(b, m.zero) == b)
assert(m.op(m.zero, b) == b)
}
opTests.foreach { case ((a,b), r) => testOneExample(a,b,r) }
val allTestInputs = opTests.flatMap {case((a,b), r) => List(a,b,r)}
val allTriples = allTestInputs.distinct.combinations(3).toList
def testAssociate(a: T, b: T, c: T) {
assert(m.op(m.op(a,b), c) == m.op(a, m.op(b,c)))
}
def testTriple(triple: Seq[T]) {
triple.toList.permutations.toList.foreach {
case x1 :: x2 :: x3 :: Nil => testAssociate(x1, x2, x3)
case _ => throw new Exception
}
}
allTriples.foreach { testTriple(_) }
}
object ex10_1 {
val intAddition = new Monoid[Int] {
def op(x1: Int, x2: Int) = x1 + x2
val zero: Int = 0
}
val intMultiplication = new Monoid[Int] {
def op(x1: Int, x2: Int) = x1 * x2
val zero: Int = 1
}
val booleanOr = new Monoid[Boolean] {
def op(x1: Boolean, x2: Boolean) = x1 || x2
val zero: Boolean = false
}
val booleanAnd = new Monoid[Boolean] {
def op(x1: Boolean, x2: Boolean) = x1 && x2
val zero: Boolean = true
}
def test {
testMonoid(intAddition, (1,1) -> 2, (1,2) -> 3)
testMonoid(intMultiplication, (2,3) -> 6, (10,5) -> 50)
testMonoid(booleanOr,
(true,true) -> true, (true,false) -> true,
(false, false) -> false)
testMonoid(booleanAnd,
(true, true) -> true, (true, false) -> false,
(false, false) -> false)
}
}
object ex10_2 {
def optionMonoid[T] = new Monoid[Option[T]] {
def op(x: Option[T], y: Option[T]): Option[T] =
x.orElse(y)
val zero: Option[T] = None
}
def test {
val intOptionMonoid: Monoid[Option[Int]] = optionMonoid
testMonoid(intOptionMonoid,
(Some(1), Some(2)) -> Some(1),
(Some(2), Some(1)) -> Some(2),
(None, Some(3)) -> Some(3))
}
}
def dual[T](m: Monoid[T]): Monoid[T] = new Monoid[T] {
def op(x: T, y: T): T = m.op(y, x)
val zero = m.zero
}
object ex10_3 {
def endoMonoid[T] = new Monoid[T => T] {
def op(fa: T => T, fb: T => T): T => T =
x => fa(fb(x))
val zero: T => T = x => x
}
def function1CompositionMonoid[T] = endoMonoid[T]
def function1AndThenMonoid[T] = dual(endoMonoid[T])
def test {
// how would I?
// actually should use the foldMap and such
}
}
object ex10_4 {
def test {
println("Missing exercise 10.4\n")
}
}
object ex10_5 {
def foldMap[A, B](as: List[A], m: Monoid[B])(f: A => B): B =
as.foldLeft(m.zero)((b, a) => m.op(b, f(a)))
}
object ex10_6 {
import ex10_5.foldMap
import ex10_3.{function1CompositionMonoid, function1AndThenMonoid}
def foldRight[T, R](xs: List[T], zero: R)(op: (T, R) => R): R = {
val composedFunc =
foldMap(
xs, function1CompositionMonoid[R])(
(element: T) => (accumulatedSoFar: R) => op(element, accumulatedSoFar))
composedFunc(zero)
}
def foldLeft[T, R](xs: List[T], zero: R)(op: (R, T) => R): R = {
val composedFunc =
foldMap(
xs, function1AndThenMonoid[R])(
(element: T) => (accumulatedSoFar: R) => op(accumulatedSoFar, element))
composedFunc(zero)
}
def test {
val xs = List(1,2,3)
def testRight {
val summed = foldRight(xs, 0)(_ + _)
assert(summed == 6)
val reconstituted = foldRight(xs, Nil: List[Int])(_ :: _)
assert(reconstituted == xs)
}
testRight
def testLeft {
val summed = foldLeft(xs, 0)(_ + _)
assert(summed == 6)
val reversed = foldLeft(xs, Nil: List[Int])((revd, elem) => elem :: revd)
assert(reversed == xs.reverse)
}
testLeft
}
}
object ex10_7 {
def foldMap[A, B](v: IndexedSeq[A], m: Monoid[B])(f: A => B): B = {
if (v.length == 0) {
m.zero
} else if (v.length == 1) {
f(v(0))
} else {
val (left, right) = v.splitAt(v.length / 2)
val leftResult = foldMap(left, m)(f)
val rightResult = foldMap(right, m)(f)
m.op(leftResult, rightResult)
}
}
def test {
// import ex10_1.intAddition
val xs = Vector(1,2,3,4)
val aslist = foldMap(xs, listMonoid[Int])(x => List(x, x))
assert(aslist == List(1,1,2,2,3,3,4,4))
}
}
object ex10_9 {
case class Bounds(min: Int, max: Int)
def combine(b1: Bounds, b2: Bounds) =
Bounds(b1.min min b2.min, b1.max max b2.max)
case class OrderingInfo(bounds: Bounds, ordered: Boolean)
def adjoin(left: OrderingInfo, right: OrderingInfo): OrderingInfo = {
val OrderingInfo(lb, lordered) = left
val OrderingInfo(rb, rordered) = right
val ordered = lordered && rordered && (lb.max <= rb.min)
val bounds = combine(lb, rb)
OrderingInfo(bounds, ordered)
}
val orderingMonoid = new Monoid[Option[OrderingInfo]] {
def op(l: Option[OrderingInfo], r: Option[OrderingInfo]) = {
val combined =
l.flatMap(loinfo =>
r.map(roinfo => adjoin(loinfo, roinfo)))
combined orElse l orElse r
}
def zero = None: Option[OrderingInfo]
}
import ex10_7.foldMap
def isOrdered(v: IndexedSeq[Int]): Boolean = {
val oInfo = foldMap(v, orderingMonoid)(
x => Some(OrderingInfo(Bounds(x,x), true)))
oInfo match {
case Some(OrderingInfo(_, ordered)) => ordered
case None => true
}
}
def test {
assert(isOrdered(Vector(1,2,3,10)))
assert(!isOrdered(Vector(1,2,10,3)))
assert(isOrdered(Vector[Int]()))
}
}
object ex10_10 {
sealed trait WC
case class Stub(chars: String) extends WC
case class Part(
lStub: String, words: Int, rStub: String) extends WC
// if a lStub combines with an rStub that makes a new word.
def combine(x: WC, y: WC): WC =
(x,y) match {
case (Part(l1, w1, r1), Part(l2, w2, r2)) => {
if (r1 == "" && l2 == "") {
Part(l1, w1 + w2, r2)
} else Part(l1, w1 + w2 + 1, r2)
}
case (Part(l1, w1, r1), Stub(r)) =>
Part(l1, w1, r1 + r)
case (Stub(l), Part(l2, w2, r2)) =>
Part(l + l2, w2, r2)
case (Stub(l), Stub(r)) => Stub(l + r)
}
val wcMonoid = new Monoid[WC] {
def op(x: WC, y: WC): WC = combine(x, y)
def zero = Stub("")
}
def charToWC(c: Char): WC = {
if (c.toString.trim == "") {
Part("", 0, "")
} else Stub(c.toString)
}
import ex10_7.foldMap
def countWords(x: String): Int = {
val theCount: WC = foldMap(x, wcMonoid)(charToWC(_))
theCount match {
case Stub(_) => 1
case Part(lStub, words, rStub) => {
val lEdge = if (lStub == "") 0 else 1
val rEdge = if (rStub == "") 0 else 1
words + lEdge + rEdge
}
}
}
}
object ex10_11 {
import ex10_10.countWords
def test {
assert(countWords("Mary had a") == 3)
assert(countWords(" ") == 0)
assert(countWords(" lobster sticks ") == 2)
}
}
import scala.language.higherKinds
trait Foldable[F[_]] {
def foldRight[A,B](as: F[A])(z: B)(f: (A,B) => B): B
def foldLeft[A,B](as: F[A])(z: B)(f: (B,A) => B): B
def foldMap[A,B](as: F[A])(f: A => B)(mb: Monoid[B]): B
def concatenate[A](as: F[A])(m: Monoid[A]): A =
foldLeft(as)(m.zero)(m.op)
def toList[A](as: F[A]): List[A] = foldRight(as)(Nil: List[A])(_ :: _)
}
object ex10_12 {
val listFolding = new Foldable[List] {
def foldRight[A,B](as: List[A])(z: B)(f: (A,B) => B): B =
as.foldRight(z)(f)
def foldLeft[A,B](as: List[A])(z: B)(f: (B,A) => B): B =
as.foldLeft(z)(f)
def foldMap[A,B](as: List[A])(f: A => B)(mb: Monoid[B]): B =
as.foldLeft(mb.zero)((b, a) => mb.op(b, f(a)))
}
println("Missing most of exercise 10.12")
}
object ex10_13 {
sealed trait Tree[+A]
case class Leaf[A](value: A) extends Tree[A]
case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]
val treeFolding = new Foldable[Tree] {
def foldRight[A,B](as: Tree[A])(z: B)(f: (A,B) => B): B = {
as match {
case Leaf(x) => f(x, z)
case Branch(left, right) =>
foldRight(left)(foldRight(right)(z)(f))(f)
}
}
def foldLeft[A,B](as: Tree[A])(z: B)(f: (B,A) => B): B = {
as match {
case Leaf(x) => f(z, x)
case Branch(left, right) =>
foldLeft(right)(foldLeft(left)(z)(f))(f)
}
}
def foldMap[A,B](as: Tree[A])(f: A => B)(mb: Monoid[B]): B = {
as match {
case Leaf(x) => f(x)
case Branch(left, right) =>
mb.op(foldMap(left)(f)(mb), foldMap(right)(f)(mb))
}
}
}
}
object ex10_14 {
val optionFolding = new Foldable[Option] {
def foldRight[A,B](as: Option[A])(z: B)(f: (A,B) => B): B =
as match {
case Some(a) => f(a, z)
case None => z
}
def foldLeft[A,B](as: Option[A])(z: B)(f: (B,A) => B): B =
as match {
case Some(a) => f(z, a)
case None => z
}
def foldMap[A,B](as: Option[A])(f: A => B)(mb: Monoid[B]): B =
as match {
case Some(a) => f(a)
case None => mb.zero
}
}
def test {
val x = Some(3)
val notx = None
assert(optionFolding.foldRight(x)(Nil: List[Int])(_ :: _) == List(3))
assert(optionFolding.foldRight(notx)(Nil: List[Int])(_ :: _) == List[Int]())
}
}
object ex10_15 {
def test {
import ex10_13.{Tree, Leaf, Branch, treeFolding}
val l = Branch(Leaf(1), Leaf(2))
val r = Branch(Leaf(3), Leaf(4))
val t = Branch(l, r)
val tasList = treeFolding.toList(t)
assert(tasList == List(1,2,3,4))
}
}
object ex10_16 {
def productMonoid[A,B](ma: Monoid[A], mb: Monoid[B]) =
new Monoid[(A,B)] {
def op(x: (A,B), y: (A,B)): (A,B) =
(ma.op(x._1, y._1), mb.op(x._2, y._2))
val zero = (ma.zero, mb.zero)
}
}
def mapMergeMonoid[K, V](valueMonoid: Monoid[V]) =
new Monoid[Map[K, V]] {
def zero = Map[K,V]()
def op(a: Map[K,V], b: Map[K,V]): Map[K,V] = {
val allKeys = a.keySet ++ b.keySet
def combineValuesForKey(key: K): V = {
val fromA = a.getOrElse(key, valueMonoid.zero)
val fromB = b.getOrElse(key, valueMonoid.zero)
valueMonoid.op(fromA, fromB)
}
val emptyMap = zero
def addCombinedToMap(theMap: Map[K,V], key: K) =
theMap.updated(key, combineValuesForKey(key))
allKeys.foldLeft(emptyMap)(addCombinedToMap(_,_))
}
}
object ex10_17 {
import ex10_1.intAddition
def functionMonoid[A,B](mb: Monoid[B]): Monoid[A => B] =
new Monoid[A => B] {
def zero =
x => mb.zero
def op(f1: A => B, f2: A => B) =
x => mb.op(f1(x), f2(x))
}
def test {
val stringCountMonoid: Monoid[Map[String, Int]] =
mapMergeMonoid(intAddition)
val m1 = Map("cat" -> 2, "dog" -> 4)
val m2 = Map("parrot" -> 1, "dog" -> 3)
val m12 = stringCountMonoid.op(m1, m2)
assert(m12.getOrElse("dog", 0) == 4 + 3)
assert(m12.getOrElse("cat", 0) == 2)
assert(m12.getOrElse("parrot", 0) == 1)
}
}
object ex10_18 {
import ex10_1.intAddition
import ex10_7.foldMap
def bag[A](as: IndexedSeq[A]): Map[A, Int] = {
val baggingMonoid = mapMergeMonoid[A, Int](intAddition)
foldMap(as, baggingMonoid)(x => Map(x -> 1))
}
def test {
val bagged = bag(Vector("a", "rose", "is", "a", "rose"))
assert(bagged("rose") == 2)
assert(bagged("is") == 1)
}
}
def main(args: Array[String]) {
ex10_1.test
ex10_2.test
ex10_3.test
ex10_4.test
ex10_6.test
ex10_7.test
ex10_9.test
ex10_11.test
ex10_14.test
ex10_15.test
ex10_17.test
ex10_18.test
}
}