Class with list Nat between 0 and 2?

Using Peter Neyens help answer , I tried to create a class Xthat consists only of Natless than or equal to 2.

import shapeless._
import shapeless.ops.nat._
import shapeless.nat._

case class X[A <: Nat](values: List[A])(implicit ev: LTEq[A, _2])

The following works:

scala> X( List(_1, _1, _1) )
res6: X[shapeless.nat._1] = X(List(Succ(), Succ(), Succ()))

But when I used different ones Nat, i.e. _1and _2, I got a compile time error:

scala> X( List(_1, _2) )
<console>:23: error: could not find implicit value for parameter ev: 
   shapeless.ops.nat.LTEq[shapeless.Succ[_ >: shapeless.Succ[shapeless._0] 
       with shapeless._0 <: Serializable with shapeless.Nat],shapeless.nat._2]
       X( List(_1, _2) )
        ^

Then I tried:

scala> case class X(values: List[_ <: Nat])
defined class X

which works for sub-classesof Natbut it is not limited <= 2:

scala> X(List(_1, _2, _3))
res8: X = X(List(Succ(), Succ(), Succ()))

How can I write mine above Xwhich has a list Natthat fall in a range 0 to 2?

My immediate thought is to use the Algebraic data type for MyZero, MyOneand MyTwo, but not sure, the cleanest way.

, , X . X?

+2
1

ADT , , , , , .

, < <=, - Nat , int Nat.

, NatOps toInt.

, Nat, Literal(Constant()).

val n = i.tree match {
  case Literal(Constant(n: Int)) => n
  case _ =>
    c.abort(c.enclosingPosition, s"Expression ${i.tree} does not evaluate to an Int constant")
}

, , , - :

abstract class SizeBound[N <: Nat](n: N)

import shapeless.nat._

implicit object ZeroBound extends SizeBound(_0)
implicit object OneBound extends SizeBound(_1)
implicit object TwoBound extends SizeBound(_2)

def op[T <: Nat : SizeBound](...). , Shapeless , , , .

, , Shapeless Fizz , , Mod.Aux, nats.

, -:

import shapeless.ops.nat._
import shapeless.nat._

def doStuff[N <: Nat](n: N)(
  // There is a _2 type already available.
  implicit ev: LT[N, _2]
) = { // now you know N is less than _2}

LT, , , . , . , , _2.type, _2 import shapeless.nat._

+1

Source: https://habr.com/ru/post/1652700/


All Articles