List of fixed size and item restrictions

Using shapeless, I am trying to define a function:

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

def threeNatsLessThan3[N <: Nat](xs: Sized[List[N], N])
   (implicit ev: LTEq[N, _3]) = ???

where it will be compiled only if the input xsis List(size 3) Nat, where each element is <= 3.

But this does not compile:

scala> threeNatsLessThan3[_3](List(_1,_2,_3))
<console>:22: error: type mismatch;
 found   : List[shapeless.Succ[_ >: shapeless.Succ[shapeless.Succ[shapeless._0]] with shapeless.Succ[shapeless._0] with shapeless._0 <: Serializable with shapeless.Nat]]
 required: shapeless.Sized[List[shapeless.nat._3],shapeless.nat._3]
    (which expands to)  shapeless.Sized[List[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless._0]]]],shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless._0]]]]a>
       twoNatsFirstLtEqSecond[_3](List(_1,_2,_3))
                                      ^

How can I implement the above function correctly?

I would also appreciate a solution using HList, where it HListconsists only of elements Nat(if possible).

+4
source share
1 answer

, , List N, N. whit Sized[List[N], N] : List(_1), List(_2, _2) , , List(_3, _3, _3), . , , , :

required: shapeless.Sized[List[shapeless.nat._3],shapeless.nat._3]

, , , List[Nat], . Nat . , - , : HList, , Nat , List[N] List[Nat] Sized.

, List 3,

def lessThanThree[N <: Nat](sz: Sized[List[Nat], N])(implicit ev: LTEq[N, _3]) = sz

, List Nat , N List:

def lessThanThree[N <: Nat, M <: Nat](sz: Sized[List[N], M])(implicit ev: LTEq[N, _3]) = sz

Poly, at Nat, LTEq, , Sized map map, , .. CanBuildFrom. Nat List , , , .

HList, :

 object LT3Identity extends Poly{
   implicit def only[N <: Nat](implicit ev: LTEq[N, _3]) = at[N]{ i => i}
 }

 def lt3[L <: HList, M <: Nat](ls: L)(implicit lg: Length.Aux[L, M], lt: LTEq[M, _3]) = ls.map(LT3Identity)

HList 3, HList Nat 3.

+1

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


All Articles