Skip to content

Instantly share code, notes, and snippets.

@aoiroaoino
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aoiroaoino/898200e5473234831f2a to your computer and use it in GitHub Desktop.
Save aoiroaoino/898200e5473234831f2a to your computer and use it in GitHub Desktop.
trait Monoid[A] {
def zero: A
def append(x: A, y: A): A
}
trait MonoidFunctions {
implicit class MonoidFunction[A: Monoid](x: A) {
val m = implicitly[Monoid[A]]
def |+|(a: A) = m.append(x, a)
}
}
trait MonoidInstances {
implicit val intMonoid = new Monoid[Int] {
def zero = 0
def append(a: Int, b: Int) = a + b
}
implicit val stringMonoid = new Monoid[String] {
def zero = ""
def append(a: String, b: String) = a + b
}
}
object Monoid extends MonoidInstances with MonoidFunctions
/*
scala> import Monoid._
import Monoid._
scala> 1 |+| 1
res1: Int = 2
scala> "a" |+| "b"
res2: String = ab
scala> 1.0 |+| 1.0
<console>:15: error: could not find implicit value for evidence parameter of type Monoid[Double]
1.0 |+| 1.0
^
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment