Last active
August 29, 2015 14:07
-
-
Save aoiroaoino/898200e5473234831f2a to your computer and use it in GitHub Desktop.
This file contains 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
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