1
+ package ch07
2
+
3
+ /*
4
+ We can use Semigroups and Monoids by importing two things: the type classes themselves,
5
+ and the semigroup syntax to give us the |+| operator.
6
+ */
7
+ import cats .{Monoid as CatsMonoid }
8
+ import cats .syntax .semigroup .catsSyntaxSemigroup
9
+
10
+ object Lib :
11
+
12
+ /*
13
+ 7.3.3.1 Exercise: Adding All The Things
14
+ The cutting edge SuperAdder v3.5a-32 is the world's first choice for adding together numbers.
15
+ The main function in the program has signature def add(items: List[Int]): Int.
16
+ In a tragic accident this code is deleted! Rewrite the method and save the day!
17
+
18
+ SuperAdder's market share continues to grow, and now there is demand for additional functionality.
19
+ People now want to add List[Option[Int]]. Change add so this is possible. The SuperAdder code base
20
+ is of the highest quality, so make sure there is no code duplication!
21
+ */
22
+ def add [A : CatsMonoid as m](items : List [A ]): A =
23
+ items.foldLeft(m.empty)(_ |+| _)
24
+
25
+ // import cats.instances.int.catsKernelStdGroupForInt
26
+ // add(List(1, 2, 3))
27
+
28
+ // add(List(Some(1), None, Some(2), None, Some(3)))
29
+
30
+ // Doesn't compile: No given instance of type cats.kernel.Monoid[Some[Int]] was found.
31
+ // The inferred type of the list is List[Some[Int]], Cats Monoid is invariant, so,
32
+ // Monoid[Option[A]] is not applicable.
33
+ // add(List(Some(1), Some(2), Some(3)))
34
+
35
+ /*
36
+ SuperAdder is entering the POS (point-of-sale, not the other POS) market.
37
+ Now we want to add up Orders.
38
+
39
+ We need to release this code really soon so we can’t make any modifications to add.
40
+ Make it so!
41
+ */
42
+ case class Order (totalCost : Double , quantity : Double )
43
+
44
+ given Monoid [Order ]:
45
+ def combine (o1 : Order , o2 : Order ) =
46
+ Order (
47
+ o1.totalCost + o2.totalCost,
48
+ o1.quantity + o2.quantity
49
+ )
50
+
51
+ def empty = Order (0 , 0 )
0 commit comments