Skip to content

Instantly share code, notes, and snippets.

@deanwampler
Last active February 13, 2021 17:29
Show Gist options
  • Save deanwampler/2ed5c04f95b2356275d82f6312b574a0 to your computer and use it in GitHub Desktop.
Save deanwampler/2ed5c04f95b2356275d82f6312b574a0 to your computer and use it in GitHub Desktop.
scala> import scala.annotation.targetName
scala> trait Semigroup[T]: // also used in other examples for Type Classes
| extension (t: T)
| infix def combine(other: T): T
| @targetName("plus") def <+>(other: T): T = t.combine(other)
|
| trait Monoid[T] extends Semigroup[T]:
| def unit: T
scala> given NumericMonoid2[T : Numeric]: Monoid[T] = new Monoid[T]:
| println("Initializing NumericMonoid2")
| def unit: T = summon[Numeric[T]].zero
| extension (t: T) infix def combine(other: T): T =
| summon[Numeric[T]].plus(t, other)
def NumericMonoid2[T](using evidence$1: Numeric[T]): Monoid[T]
scala> given StringMonoid2: Monoid[String] = new Monoid[String]:
| println("Initializing StringMonoid2")
| def unit: String = ""
| extension (s: String)
| infix def combine(other: String): String = s + other
lazy val StringMonoid2: Monoid[String]
// Use them. Note the output:
scala> 2.2 <+> (3.3 <+> 4.4) // 9.9
| (2.2 <+> 3.3) <+> 4.4 // 9.9
Initializing NumericMonoid2
Initializing NumericMonoid2
Initializing NumericMonoid2
Initializing NumericMonoid2
val res0: Double = 9.9
val res1: Double = 9.9
scala> "2" <+> ("3" <+> "4") // "234"
| ("2" <+> "3") <+> "4" // "234"
Initializing StringMonoid2
val res2: String = 234
val res3: String = 234
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment