Skip to content

Instantly share code, notes, and snippets.

@ahjohannessen
Created February 23, 2018 17:55
Show Gist options
  • Save ahjohannessen/e09083491a6262038be8c2789363b076 to your computer and use it in GitHub Desktop.
Save ahjohannessen/e09083491a6262038be8c2789363b076 to your computer and use it in GitHub Desktop.
Semigroup sum of disjunction
/**
* Sums up values inside disjunction, if both are left or right. Returns first left otherwise.
* {{{
* \/-(v1) +++ \/-(v2) → \/-(v1 + v2)
* \/-(v1) +++ -\/(v2) → -\/(v2)
* -\/(v1) +++ \/-(v2) → -\/(v1)
* -\/(v1) +++ -\/(v2) → -\/(v1 + v2)
* }}}
*/
def +++(x: => A \/ B)(implicit M1: Semigroup[B], M2: Semigroup[A]): A \/ B =
this match {
case -\/(a1) => x match {
case -\/(a2) => -\/(M2.append(a1, a2))
case \/-(_) => this
}
case \/-(b1) => x match {
case b2 @ -\/(_) => b2
case \/-(b2) => \/-(M1.append(b1, b2))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment