如何使用无形拆分scala列表

Pet*_*ris 6 scala shapeless

我试图在N处拆分大小为S的列表,其中已知N,M总和为S.这不编译:

def splitIt[N <: Nat,
            M <: Nat,
            S <: Nat](u: Sized[List[Int], N] {type A = N},
                      v: Sized[List[Int], M] {type A = M},
                      t: Sized[List[Int], S] {type A = S})(implicit sum: SumAux[N, M, S]): Unit = {
  val z = t.splitAt[N]
}
Run Code Online (Sandbox Code Playgroud)

错误

No implicit view available from List[Int] => scala.collection.GenTraversableLike[S,List[Int]].

not enough arguments for method sizedOps: (implicit evidence$2: List[Int] => scala.collection.GenTraversableLike[S,List[Int]])shapeless.SizedOps[S,List[Int],S]. Unspecified value parameter evidence$2.
Run Code Online (Sandbox Code Playgroud)

最终正确的版本

def splitIt[N <: Nat,
            M <: Nat, S <: Nat](u: Sized[List[Int], N] {type A = Int},
                                v: Sized[List[Int], M] {type A = Int},
                                t: Sized[List[Int], S] {type A = Int})(implicit sum: DiffAux[S, N, M], toInt: ToInt[N]): Unit = {
  val z = t.splitAt[N]
}
Run Code Online (Sandbox Code Playgroud)

Pth*_*ame 5

type A需求是在列表的元素的类型,而不是大小参数一次.这就是为什么它试图转换为GenTraversableLike[A, List[Int]].您需要设置AInt在每种情况下.

  • +1,但这只是第一步 - 知道`SumAux [N,M,S]`不会得到你需要拆分列表的'Diff [S,N]`(不幸的是),你会还必须为`N`添加一个`ToInt`. (2认同)
  • @Peteris:您可以删除`SumAux`(除非您在实际代码中出于其他原因需要它)并添加`Diff [S,N]`或`DiffAux [S,N,M]`. (2认同)