Created
March 14, 2018 01:02
-
-
Save afsalthaj/89ba91c6e81c3d813dc4a7a286f11caa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tech | |
trait Mondoid[T] { | |
def zero: T | |
def append(a: T, b: T): T | |
} | |
object Mondoid { | |
def apply[A](implicit instance: Mondoid[A]): Mondoid[A] = instance | |
} | |
package syntax { | |
import scalaz.Foldable | |
trait MondoidSyntax { | |
implicit class MondoidOps[F[_] : Foldable, A](xs: F[A]) { | |
def calcSum(implicit m: Mondoid[A]) = { | |
Foldable[F].foldLeft(xs, m.zero)(m.append) | |
} | |
} | |
} | |
} | |
package std { | |
trait MondoidInstances { | |
implicit object `Mondoid for Int` extends Mondoid[Int] { | |
def zero = 0 | |
def append(a: Int, b: Int) = a + b | |
} | |
implicit object `Mondoid for String` extends Mondoid[String] { | |
def zero = "" | |
def append(a: String, b: String) = a + b | |
} | |
} | |
} | |
package all { | |
import tech.std.MondoidInstances | |
import tech.syntax.MondoidSyntax | |
object mondoid extends MondoidInstances with MondoidSyntax | |
} | |
object TestMondoid { | |
def main(args: Array[String]): Unit = { | |
import all.mondoid._ | |
import scalaz.std.list._ | |
import scalaz.std.vector._ | |
println(List(1, 2, 3).calcSum) | |
println(Vector(1, 2, 3).calcSum) | |
println(List("1", "2", "3").calcSum) | |
println(Vector("1", "2", "3").calcSum) | |
implicit object `Mondoid for Boolean` extends Mondoid[Boolean] { | |
def zero = true | |
def append(a: Boolean, b: Boolean) = a && b | |
} | |
println(List(true, true, false).calcSum) | |
println(Vector(true, true, false).calcSum) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We love the type class, its syntax and operations. We do this inconsistently in our code base. I got this from a senior engineer in my company. Thanks to him.