Skip to content

Instantly share code, notes, and snippets.

@tixxit
Last active December 23, 2015 00:09
Show Gist options
  • Save tixxit/6552183 to your computer and use it in GitHub Desktop.
Save tixxit/6552183 to your computer and use it in GitHub Desktop.
sealed trait WithFallback[+A, +B] {
def fold[C](f: A => C, g: B => C): C
}
case class Preferred[+A](a: A) extends WithFallback[A, Nothing] {
def fold[C](f: A => C, g: B => C): C = f(a)
}
case class Fallback[+B](b: B) extends WithFallback[Nothing, B] {
def fold[C](f: A => C, g: B => C): C = g(b)
}
trait WithFallbackLow {
implicit def fallback[A, B](implicit fb: B): WithFallback[A, B] = Fallback(fb)
}
object WithFallback extends WithFallbackLow {
implicit def preferred[A, B](implicit pa: A): WithFallback[A, B] = Preferred(pa)
}
...
def reduce[A](implicit st: CMonoid[A] WithFallback Monoid[A]) = st.fold({ implicit m => ... }, { implicit m => ... })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment