简体   繁体   中英

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]) . But I think it is good to constraint the lengths if it is possible, for an IDE and/or a compiler can enforce it. 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.

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?

As a last resort you could define special cases for the allowable sizes, separated so that you don't have 25 cases:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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