Kevin Meredith Kevin Meredith - 3 months ago 16
Scala Question

Enforce Bounded Nat?

How can I enforce a

Nat
that's
<= N
?

Example:

def lessThan5(x: NatLT5) = ???


where

lessThan5(Nat(4))
would compile, but
lessThan5(Nat(6))
would not.

Answer

You can use the type class LTEq (or LT if you want strictly less than).

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

def lessThan5[N <: Nat](n: N)(implicit ev: LTEq[N, _5]) = ???

lessThan5(_4) // compiles
lessThan5(_5) // compiles
lessThan5(_6) // doesn't compile because LTEq[_6, _5] cannot be found
Comments