|
| 1 | +package algebra |
| 2 | + |
| 3 | +import scala.annotation.nowarn |
| 4 | + |
| 5 | +/** |
| 6 | + * Priority is a type class for prioritized implicit search. |
| 7 | + * |
| 8 | + * This type class will attempt to provide an implicit instance of `P` |
| 9 | + * (the preferred type). If that type is not available it will |
| 10 | + * fallback to `F` (the fallback type). If neither type is available |
| 11 | + * then a `Priority[P, F]` instance will not be available. |
| 12 | + * |
| 13 | + * This type can be useful for problems where multiple algorithms can |
| 14 | + * be used, depending on the type classes available. |
| 15 | + */ |
| 16 | +sealed trait Priority[+P, +F] { |
| 17 | + |
| 18 | + import Priority.{Fallback, Preferred} |
| 19 | + |
| 20 | + def fold[B](f1: P => B)(f2: F => B): B = |
| 21 | + this match { |
| 22 | + case Preferred(x) => f1(x) |
| 23 | + case Fallback(y) => f2(y) |
| 24 | + } |
| 25 | + |
| 26 | + def join[U >: P with F]: U = |
| 27 | + fold(_.asInstanceOf[U])(_.asInstanceOf[U]) |
| 28 | + |
| 29 | + def bimap[P2, F2](f1: P => P2)(f2: F => F2): Priority[P2, F2] = |
| 30 | + this match { |
| 31 | + case Preferred(x) => Preferred(f1(x)) |
| 32 | + case Fallback(y) => Fallback(f2(y)) |
| 33 | + } |
| 34 | + |
| 35 | + def toEither: Either[P, F] = |
| 36 | + fold[Either[P, F]](p => Left(p))(f => Right(f)) |
| 37 | + |
| 38 | + def isPreferred: Boolean = |
| 39 | + fold(_ => true)(_ => false) |
| 40 | + |
| 41 | + def isFallback: Boolean = |
| 42 | + fold(_ => false)(_ => true) |
| 43 | + |
| 44 | + def getPreferred: Option[P] = |
| 45 | + fold[Option[P]](p => Some(p))(_ => None) |
| 46 | + |
| 47 | + def getFallback: Option[F] = |
| 48 | + fold[Option[F]](_ => None)(f => Some(f)) |
| 49 | +} |
| 50 | + |
| 51 | +object Priority extends FindPreferred { |
| 52 | + |
| 53 | + case class Preferred[P](get: P) extends Priority[P, Nothing] |
| 54 | + case class Fallback[F](get: F) extends Priority[Nothing, F] |
| 55 | + |
| 56 | + def apply[P, F](implicit ev: Priority[P, F]): Priority[P, F] = ev |
| 57 | +} |
| 58 | + |
| 59 | +private[algebra] trait FindPreferred extends FindFallback { |
| 60 | + @nowarn("msg=deprecated") |
| 61 | + implicit def preferred[P](implicit ev: P): Priority[P, Nothing] = |
| 62 | + Priority.Preferred(ev) |
| 63 | +} |
| 64 | + |
| 65 | +private[algebra] trait FindFallback { |
| 66 | + @nowarn("msg=deprecated") |
| 67 | + implicit def fallback[F](implicit ev: F): Priority[Nothing, F] = |
| 68 | + Priority.Fallback(ev) |
| 69 | +} |
0 commit comments