以 Nat 表示的 HList 类型参数的长度 [英] The length of HList type paremeter in terms of Nat
问题描述
假设我有一个没有参数的方法.如何确定类型参数的长度?
Suppose I have a method without params. How can I determine a length of type parameter?
def func[T <: HList]: Nat = {
// some magic
}
推荐答案
您可以使用 ops.hlist.Length
操作来计算 的
.Nat
长度HList
You can use ops.hlist.Length
operation to calculate the Nat
length of an HList
.
此外,将其作为不透明的 Nat
并不是很有用,因为您会丢失有关实际数字的所有类型级信息.所以你必须从函数中获取准确的 Nat
类型:
Also, getting it as an opaque Nat
is not very useful, because you lose all the type-level information about the actual number. So you have to get the exact Nat
type from the function:
import shapeless._
import shapeless.ops.hlist.Length
def func[T <: HList](implicit len: Length[T]): len.Out = len()
用法:
scala> natLen[Int :: String :: HNil]
res1: shapeless.Succ[shapeless.Succ[shapeless._0]] = Succ()
<小时>
获取长度为 Int
似乎更棘手.看来你不能使用 ops.nat.ToInt
,因为它需要一个 N <: Nat
类型参数并且基本上使它无用:
Getting the length as an Int
seems more tricky. It seems you can't use ops.nat.ToInt
, because it would require a N <: Nat
type parameter and basically make it useless:
def uselessIntLen[T <: HList, N <: Nat](implicit
len: Length.Aux[T, N],
toInt: ToInt[N]
): Int = toInt()
我使用 HKernel
找到了以下解决方法(当然,也可以手动编写新的类型类 IntLength
).也许有人可以帮助提供更直接的内置方法:
I've found the following workaround using HKernel
(of course, it's also possible to write a new typeclass IntLength
manually). Maybe someone can help with a more direct built-in method:
import shapeless.ops.hlist.HKernelAux
def intLen[T <: HList](implicit ker: HKernelAux[T]): Int = ker().length
用法:
scala> intLen[Int :: String :: HNil]
res2: Int = 2
这篇关于以 Nat 表示的 HList 类型参数的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!