Skip to content

Instantly share code, notes, and snippets.

@Biacco42
Created May 25, 2017 16:45
Show Gist options
  • Save Biacco42/dd27c9378dc10748aef90141170a4c0a to your computer and use it in GitHub Desktop.
Save Biacco42/dd27c9378dc10748aef90141170a4c0a to your computer and use it in GitHub Desktop.
TypeClass PlayGround
package info.biacco42.test.typeclass
/**
* Created by sanok on 2017/05/25.
*/
trait Addable[T] {
val unit: T
def add(x: T, y: T): T
}
object Instance {
implicit object IntAddable extends Addable[Int] {
override val unit: Int = 0
override def add(x: Int, y: Int): Int = x + y
}
implicit object StringAddable extends Addable[String] {
override val unit: String = ""
override def add(x: String, y: String): String = x + y
}
}
object TypeClassPlayGround {
import Instance._
def main(args: Array[String]): Unit = {
val intList = List(1, 2, 3)
val stringList = List("hoge", "piyo", "huga")
println("\nOver load")
println(sumOverLoad(intList))
println(sumOverLoad(stringList))
println("\nStrategy")
println(sumStrategy(intList)(IntAddStrategy))
println(sumStrategy(stringList)(StringAddStrategy))
println("\nType Class")
println(sumTypeClass(intList))
println(sumTypeClass(stringList))
}
def sumOverLoad(xs: List[Int]): Int = xs match {
case Nil => 0
case x :: xs => x + sumOverLoad(xs)
}
def sumOverLoad(xs: List[String]): String = xs match {
case Nil => ""
case x :: xs => x + sumOverLoad(xs)
}
def sumStrategy[T](xs: List[T])(strategy: AddStrategy[T]): T = xs match {
case Nil => strategy.unit
case x :: xs => strategy.add(x, sumStrategy(xs)(strategy))
}
def sumTypeClass[T](xs: List[T])(implicit addable: Addable[T]): T = xs match {
case Nil => addable.unit
case x :: xs => addable.add(x, sumTypeClass(xs)(addable))
}
}
trait AddStrategy[T] {
val unit: T
def add(x: T, y: T): T
}
object IntAddStrategy extends AddStrategy[Int] {
override val unit: Int = 0
override def add(x: Int, y: Int): Int = x + y
}
object StringAddStrategy extends AddStrategy[String] {
override val unit: String = ""
override def add(x: String, y: String): String = x + y
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment