-
Notifications
You must be signed in to change notification settings - Fork 155
/
WitnessAs.scala
42 lines (37 loc) · 1.09 KB
/
WitnessAs.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package eu.timepit.refined.internal
import shapeless.{Nat, Witness}
import shapeless.ops.nat.ToInt
/**
* `WitnessAs[A, B]` provides the singleton value of type `A` in `fst`
* and `fst` converted to type `B` in `snd`.
*
* The purpose of this type class is to write numeric type class
* instances that work with both literal singleton types and
* `shapeless.Nat`.
*
* Example: {{{
* scala> import eu.timepit.refined.W
* | import shapeless.nat._5
*
* scala> WitnessAs[W.`5`.T, Int]
* res1: WitnessAs[W.`5`.T, Int] = WitnessAs(5,5)
*
* scala> WitnessAs[_5, Int]
* res2: WitnessAs[_5, Int] = WitnessAs(Succ(),5)
* }}}
*/
final case class WitnessAs[A, B](fst: A, snd: B)
object WitnessAs {
def apply[A, B](implicit ev: WitnessAs[A, B]): WitnessAs[A, B] = ev
implicit def natWitnessAs[B, A <: Nat](
implicit
wa: Witness.Aux[A],
ta: ToInt[A],
nb: Numeric[B]
): WitnessAs[A, B] =
WitnessAs(wa.value, nb.fromInt(ta.apply()))
implicit def singletonWitnessAs[B, A <: B](
implicit wa: Witness.Aux[A]
): WitnessAs[A, B] =
WitnessAs(wa.value, wa.value)
}