How to limit the maximum length of a list in an argument definition?

My function should take from zero to five integer arguments and from zero to five arguments to a string. Therefore, I consider it as a function of 2 lists: f(numbers: List[Int], strings: List[String]) . But I think it is useful to limit lengths if possible, since the IDE and / or the compiler can use it. Is it possible?

+4
source share
1 answer

I think that you really define many type systems for this ... This is a classic task for typed programming, which unfortunately does not include the Scala category.

You can look at Naturals at the Mark Harrah font level :

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

But if you go down this route, you will need to collect all your lists in such a way that the length type is obvious to the compiler. This means no recursion, no unlimited loop, etc. You will also have to come up with a way to encode "<" in the type system ... since you cannot perform recursion, I'm not sure how you will do it. So it’s probably not worth it.

Maybe another way to approach the problem is to find out where "0..5" comes from and restrain some other type based on this information?

As a last resort, you can define special cases for allowable sizes, divided 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)) 
+7
source

Source: https://habr.com/ru/post/1382107/


All Articles