44
|
1 |
package Main
|
|
2 |
|
|
3 |
abstract class SemiGroup[A] {
|
|
4 |
def add(x: A, y: A): A
|
|
5 |
}
|
|
6 |
|
|
7 |
abstract class Monoid[A] extends SemiGroup[A] {
|
|
8 |
def unit: A
|
|
9 |
}
|
|
10 |
|
|
11 |
object ImplicitTest extends App {
|
|
12 |
implicit object StringMonoid extends Monoid[String] {
|
|
13 |
def add(x: String, y: String): String = x concat y
|
|
14 |
def unit: String = ""
|
|
15 |
}
|
|
16 |
|
|
17 |
implicit object IntMonoid extends Monoid[Int] {
|
|
18 |
def add(x: Int, y: Int): Int = (x + y)
|
|
19 |
def unit: Int = 0
|
|
20 |
}
|
|
21 |
|
|
22 |
def sum[A](xs: List[A])(implicit m: Monoid[A]): A =
|
|
23 |
if (xs.isEmpty) m.unit
|
|
24 |
else {
|
|
25 |
println("head: " + xs.head);
|
|
26 |
println("tail: " + xs.tail);
|
|
27 |
m.add(xs.head, sum(xs.tail))
|
|
28 |
}
|
|
29 |
|
|
30 |
println(sum(List(1, 2, 3)))
|
|
31 |
println(sum(List("a", "b", "c")))
|
|
32 |
} |