Search code examples
arraysadavariadic

Variadic Ada Functions


I'm studying Ada because I am intrigued by the idea of strict type safety and programming contracts. The idea of "programming for forever" is nice. Anyway, the real question is whether or not Ada has variadic functions. A search on SO suggests that Ada doesn't, and the correct way to do this is with an unconstrained array whose length is determined at runtime.

My question then, isn't how do you do it, but rather what is the convention for doing it correctly?

Additionally, why is it that Ada can perform (what appear to be stack-based) operations like + (e.g. 1+2+3), but it cannot do the same for arguments to a function call?

Is it more idiomatic to not do variadic expressions at all like Max(1, 2, 3, ..., n), or is it simply that you should pass the arguments to it like Args.len=n; Max(Args[])?

My instinct and what I've gleaned from reading the various Ada books suggests that you shouldn't have unspecific functions due to them being less safe.


Solution

  • As suggested here, "variadic functions can expose type-safety problems in some languages." Although Ada does not support variadic functions, the example seen here mimics the behavior using operator overloading in an array aggregate. The risk posed by a variadic parameter list typically lies in allowing raw input data to be passed directly to executable code. The interposed aggregate precludes this in Ada, while permitting the stylistic convenience.

    In the fragment below, an overloaded + function converts each string literal into an Unbounded_String, and each such Unbounded_String becomes a component of a Variadic_Array, which then becomes the sole parameter to the Print_Line function. Constraint_Error is raised if any of the prescribed checks fail.

    Print_Line((+"Mary", +"had", +"a", +"little", +"lamb."));