简体   繁体   English

如何约束参数定义中列表的最大长度?

[英]How to constraint maximum length of a list in an argument definition?

A function of mine is to take from zero to five integer arguments and from zero to five string arguments. 我的一个函数是从零到五个整数参数以及从零到五个字符串参数。 So I consider it to define as a function of 2 lists: f(numbers: List[Int], strings: List[String]) . 所以我认为它定义为2个列表的函数: f(numbers: List[Int], strings: List[String]) But I think it is good to constraint the lengths if it is possible, for an IDE and/or a compiler can enforce it. 但是我认为如果可能的话,限制长度是好的,因为IDE和/或编译器可以强制执行它。 Is this possible? 这可能吗?

I think you're really asking a lot of the type system for this one... This is a classic task for dependently typed programming, in which category Scala unfortunately does not belong. 我认为你真的要求很多这种类型的系统...这是依赖类型编程的经典任务,不幸的是Scala不属于这类。

You could look at Mark Harrah's type-level Naturals : 你可以看看马克哈拉的类型级自然

type _0 = Nat0
type _1 = Succ[_0]
type _2 = Succ[_1]
// ...

But if you go down this route, you'll have to build all your lists in such a way that the length-type is evident to the compiler. 但是如果沿着这条路走下去,你将不得不以这样的方式构建所有列表,使得编码器的长度类型很明显。 That means no recursion, no unbounded looping, etc. Also you'll have to come up with a way to encode "<" in the type system... since you can't do recursion I'm not sure how you'd do that. 这意味着没有递归,没有无限循环等。此外,你必须想出一种在类型系统中编码“<”的方法...因为你不能做递归我不知道你是怎么做的去做。 So, probably not worth it. 所以,可能不值得。

Maybe another way to approach the problem is to figure out where '0..5' comes from and constrain some other type based on that information? 也许解决这个问题的另一种方法是弄清楚'0..5'来自何处并基于该信息约束其他类型?

As a last resort you could define special cases for the allowable sizes, separated so that you don't have 25 cases: 作为最后的手段,您可以为允许的大小定义特殊情况,分开以便您没有25个案例:

case class Small[+X](l: List[X])

def small(): Small[Nothing] = Small(List())
def small[A](a: A): Small[A] = Small(List(a))
def small[A](a1: A, a2: A): Small[A] = Small(List(a1,a2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM