构建 Nat N 的固定大小列表 [英] Building Fixed Size List of Nat N
问题描述
我试图定义一个函数,给定一个 N <: Nat
类型参数,它会构建一个正好包含 3 个 N
的 List.
I tried to define a function that, given a N <: Nat
type parameter, builds a List with exactly 3 N
's.
import shapeless._
import shapeless.nat._
scala> def natNOfSize3[N <: Nat](n: Nat): Sized[List[N], _3] =
Sized[List, _3](List(n, n, n))
<console>:17: error: wrong number of type parameters for overloaded method value apply with alternatives:
[CC[_]]()(implicit cbf: scala.collection.generic.CanBuildFrom[Nothing,Nothing,CC[Nothing]], implicit ev: shapeless.AdditiveCollection[CC[Nothing]])shapeless.Sized[CC[Nothing],shapeless._0] <and>
[CC[_]]=> shapeless.SizedBuilder[CC]
def natNOfSize3[N <: Nat](n: Nat): Sized[List[N], _3] = Sized[List, _3](List(n, n, n)) ^
但我不明白为什么它失败了.
But I don't understand why it failed.
推荐答案
一个问题是你的 n
被输入为 Nat
,而不是 N
>——我认为这只是一个错字.一旦你解决了这个问题,你可以像这样编写方法:
One issue is that your n
is typed as Nat
, not N
—I assume that's just a typo. Once you've fixed that, you can write the method like this:
import shapeless._, nat._
def natNOfSize3[N <: Nat](n: N): Sized[List[N], _3] = Sized[List](n, n, n)
请注意,Sized.apply
接受类型为 * -> 的单个类型参数.*
,而不是提供集合,而是提供元素.
Note that Sized.apply
takes a single type parameter of kind * -> *
, and instead of providing a collection, you provide the elements.
如果你真的想传入一个集合,你可以使用wrap
:
If you really want to pass in a collection, you could use wrap
:
def natNOfSize3[N <: Nat](n: N): Sized[List[N], _3] = Sized.wrap(List(n, n, n))
但是,如果您对元素数量撒了谎,那么编译器将无法帮助您.
But then the compiler isn't going to be able to help you if you've lied about the number of elements.
这篇关于构建 Nat N 的固定大小列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!