Last active
December 27, 2020 16:22
-
-
Save deanwampler/5f7eac8bfe678816ff4b6863ee81522a 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
// Variation of https://gist.github.com/deanwampler/e806a3301380d5d70c3247264afb076a | |
trait Semigroup[T]: | |
extension (t: T) | |
infix def combine(other: T): T // infix allows "foo combine bar". | |
def <+>(other: T): T = t.combine(other) | |
trait Monoid[T] extends Semigroup[T]: | |
def unit: T | |
// Redefine the monoid instances. Note that infix is required for the two combine definitions, even though the trait | |
// had infix. | |
given StringMonoid: Monoid[String] with | |
def unit: String = "" | |
extension (s: String) infix def combine(other: String): String = s + other | |
given IntMonoid: Monoid[Int] with | |
def unit: Int = 0 | |
extension (i: Int) infix def combine(other: Int): Int = i + other |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment