Skip to content

Instantly share code, notes, and snippets.

@matsu-chara matsu-chara/Magma.scala
Last active Aug 29, 2015

Embed
What would you like to do?
Magma
object MagmaComponent {
// マグマの定義
trait Magma[M] {
def o(m1: M, m2: M): M
}
// Magma[Int]のインスタンス定義
implicit val magmaIntInstance = new Magma[Int] {
override def o(m1: Int, m2: Int): Int = m1 + m2
}
// o(1, 2)のように呼び出せるようにしたいので便利関数を定義
def o[M: Magma](m1: M, m2: M): M = implicitly[Magma[M]].o(m1, m2)
}
object MagmaTest {
import MagmaComponent._
// 畳み込みを行う関数
def accumulate[M: Magma](a: M, bs: List[M]): M = (a, bs) match {
case (a, Nil) => a
case (a, b :: bs) => accumulate(o(a, b), bs)
}
def main (args: Array[String]) {
val result = accumulate(0, List(1, 2, 3))
println(result) // 6
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.