加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在scala中要求typeafe恒定大小的数组?

发布时间:2020-12-16 08:52:02 所属栏目:安全 来源:网络整理
导读:我需要这样的东西: def encryptBlock(arr: FixedArray[Size16]) = ??? val blocks = arr.splitFixed[Size16] val encrypted = encryptBlock(FixedArray[Size16]()) 所以,确保我只接收128位数组作为输入. 解决方法 无形可以为seqs做到这一点: import shapel
我需要这样的东西:

def encryptBlock(arr: FixedArray[Size16]) = ???
  val blocks = arr.splitFixed[Size16]
  val encrypted = encryptBlock(FixedArray[Size16]())

所以,确保我只接收128位数组作为输入.

解决方法

无形可以为seqs做到这一点:

import shapeless._
import nat._
import syntax.sized._

scala> def func(l: Sized[List[Int],_3]) = l
func: (l: shapeless.Sized[List[Int],shapeless.nat._3])shapeless.Sized[List[Int],shapeless.nat._3]

scala> List(1,2,3,4,5,6).grouped(3).map(_.sized(3).get).map(func)
res26: Iterator[shapeless.Sized[List[Int],shapeless.nat._3]] = non-empty iterator

scala> List(1,6).grouped(2).map(_.sized(2).get).map(func)
<console>:25: error: type mismatch;
 found   : shapeless.Sized[List[Int],shapeless.nat._3] => shapeless.Sized[List[Int],shapeless.nat._3]
 required: shapeless.Sized[List[Int],shapeless.Succ[shapeless.Succ[shapeless._0]]] => ?
              List(1,6).grouped(2).map(_.sized(2).get).map(func)

传递给.size的参数应该是Literal(Constant(n:Int)),因此你不能传递一些变量或表达式.

也可以将数组转换为某些IndexedSeq(.toSeq),如Vector(.toVector)

您还可以使用类型disjunction指定一组可接受的大小:

def func[A <: Nat](l: Sized[List[Int],A])(implicit ev: (_2 with _3) <:< A) = l

func(List(1,2).sized(2).get)
res17: shapeless.Sized[List[Int],shapeless.Succ[shapeless.Succ[shapeless._0]]] = shapeless.Sized@3ac1111f

scala> func(List(1,3).sized(3).get)
res18: shapeless.Sized[List[Int],shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless._0]]]] = shapeless.Sized@17191095

scala> func(List(1,4).sized(4).get)
<console>:24: error: Cannot prove that shapeless.nat._2 with shapeless.nat._3 <:< nat_1.N.
              func(List(1,4).sized(4).get)
                  ^

最大-N限制(来自@DougC和@Miles Sabin):

import ops.nat._
import LT._
scala> def func[N <: Nat](l: Sized[List[Int],N])(implicit ev: N < _3) = l
func: [N <: shapeless.Nat](l: shapeless.Sized[List[Int],N])(implicit ev: shapeless.ops.nat.LT.<[N,N]

scala> func(List(1,2).sized(2).get)
res25: shapeless.Sized[List[Int],shapeless.Succ[shapeless.Succ[shapeless._0]]] = shapeless.Sized@3ac1111f

scala> func(List(1).sized(1).get)
res26: shapeless.Sized[List[Int],shapeless.Succ[shapeless._0]] = shapeless.Sized@73f49b57

scala> func(List(1,3).sized(3).get)
<console>:30: error: could not find implicit value for parameter ev: shapeless.ops.nat.LT[nat_1.N,shapeless.nat._3]
              func(List(1,3).sized(3).get)
                  ^

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读