Advertisement
Guest User

Untitled

a guest
May 6th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.67 KB | None | 0 0
  1. abstract class SemiGroup[A] {
  2.   def add(x: A, y: A): A
  3. }
  4.  
  5. abstract class Monoid[A] extends SemiGroup[A] {
  6.   def unit: A
  7. }
  8.  
  9. object ImplicitTest extends App {
  10.  
  11.   implicit object StringMonoid extends Monoid[String] {
  12.     def add(x: String, y: String): String = x concat y
  13.     def unit: String = ""
  14.   }
  15.  
  16.   implicit object IntMonoid extends Monoid[Int] {
  17.     def add(x: Int, y: Int): Int = x + y
  18.     def unit: Int = 0
  19.   }
  20.  
  21.   def sum[A](xs: List[A])(implicit m: Monoid[A]): A =
  22.     if (xs.isEmpty) m.unit
  23.     else m.add(xs.head, sum(xs.tail))
  24.  
  25.   println(sum(List(1, 2, 3)))          // używa IntMonoid
  26.   println(sum(List("a", "b", "c")))    // używa StringMonoid
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement