Skip to content

Instantly share code, notes, and snippets.

@deanwampler
Last active February 13, 2021 15:23
Show Gist options
  • Save deanwampler/5d176eeb8f886f8c4fcf2c6dc8edab81 to your computer and use it in GitHub Desktop.
Save deanwampler/5d176eeb8f886f8c4fcf2c6dc8edab81 to your computer and use it in GitHub Desktop.
// Compare to scala2-3-MonoidTypeClassNumeric2.scala
// Anonymous givens; just remove the name!
given [T](using num: Numeric[T]): Monoid[T] with
def unit: T = num.zero
extension (t: T) def combine(other: T): T = num.plus(t, other)
// or use the _context bound_ syntax:
// given [T: Numeric]: Monoid[T] with
// def unit: T = summon[Numeric[T]].zero // Use summon to retrieve the Numeric
// extension (t: T) def combine(other: T): T = summon[Numeric[T]].plus(t, other)
2.2 <+> (3.3 <+> 4.4) // 9.9
(2.2 <+> 3.3) <+> 4.4 // 9.9
BigDecimal(3.14) <+> summon[Monoid[BigDecimal]].unit
summon[Monoid[BigDecimal]].unit <+> BigDecimal(3.14)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment