Variadic function: Difference between revisions

m
{{header|F Sharp|F#}}
m (Added Delphi reference to Free Pascal code)
m ({{header|F Sharp|F#}})
 
(35 intermediate revisions by 25 users not shown)
Line 15:
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun print-all-fn (xs)
(if (endp xs)
nil
Line 22:
 
(defmacro print-all (&rest args)
`(print-all-fn (quote ,args)))</langsyntaxhighlight>
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">public function printArgs(... args):void
{
for (var i:int = 0; i < args.length; i++)
trace(args[i]);
}</langsyntaxhighlight>
 
=={{header|Ada}}==
Line 35:
Ada doesn't have variadic functions. But you can mimic the behavior by defining a function with an unconstrained array as its parameter, i.e., an array whose length is determined at run time.
 
<langsyntaxhighlight Adalang="ada">with Ada.Strings.Unbounded, Ada.Text_IO;
 
procedure Variadic is
Line 64:
Print_Line((+"Mary", +"had", +"a", +"little", +"lamb.")); -- print five strings
Print_Line((1 => +"Rosetta Code is cooool!")); -- print one string
end;</langsyntaxhighlight>
 
Output:<pre>Mary had a little lamb.
Line 71:
=={{header|Aime}}==
Printing strings:
<langsyntaxhighlight lang="aime">void
f(...)
{
Line 90:
 
return 0;
}</langsyntaxhighlight>
Printing data of assorted types:
<langsyntaxhighlight lang="aime">void
output_date(date d)
{
Line 123:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 135:
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68">main:(
MODE STRINT = UNION(STRING, INT, PROC(REF FILE)VOID, VOID);
 
Line 151:
 
print strint(("Mary","had",1,"little",EMPTY,new line))
)</langsyntaxhighlight>
Output:
<pre>
Line 165:
AppleScript handlers have no internal access to an argument vector, but we can use AppleScript's Patterned Parameters, in the form of lists of arbitrary length for variadic positional parameters, or records for variadic named parameters.
 
<langsyntaxhighlight AppleScriptlang="applescript">use framework "Foundation"
 
-- positionalArgs :: [a] -> String
Line 259:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>"alpha
Line 275:
=={{header|Applesoft BASIC}}==
An array of parameters with a count as parameter zero can be used in a subroutine to simulate a variadic function. The values in the array should probably be cleared when the subroutine returns because the array is a global variable.
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">10 P$(0) = STR$(5)
20 P$(1) = "MARY"
30 P$(2) = "HAD"
Line 283:
70 GOSUB 90"VARIADIC FUNCTION
80 END
90 FOR I = 1 TO VAL(P$(0)) : ? P$(I) : P$(I) = "" : NEXT I : P$(0) = "" : RETURN</langsyntaxhighlight>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">;-------------------------------------------
; a quasi-variadic function
;-------------------------------------------
Line 314:
 
variable "yes"
variable.with:"something" "yes!"</langsyntaxhighlight>
 
{{out}}
Line 329:
{{works with|AutoHotkey_L}}
Writing an asterisk after the final parameter marks the function as variadic, allowing it to receive a variable number of parameters:
<langsyntaxhighlight AutoHotkeylang="autohotkey">printAll(args*) {
for k,v in args
t .= v "`n"
MsgBox, %t%
}</langsyntaxhighlight>
This function can be called with any number of arguments:<langsyntaxhighlight AutoHotkeylang="autohotkey">printAll(4, 3, 5, 6, 4, 3)
printAll(4, 3, 5)
printAll("Rosetta", "Code", "Is", "Awesome!")</langsyntaxhighlight>
An array of parameters can be passed to any function by applying the same syntax to a function-call:<langsyntaxhighlight AutoHotkeylang="autohotkey">args := ["Rosetta", "Code", "Is", "Awesome!"]
printAll(args*)</langsyntaxhighlight>
 
 
Line 344:
 
Function arguments can be given default values. Comparison with "" can indicate that an argument was present (and not of value ""). As of version 1.0.48, you can pass more parameters than defined by a function, in which case the parameters are evaluated but discarded. Versions earlier than that produce warnings.
<langsyntaxhighlight lang="autohotkey">string = Mary had a little lamb
StringSplit, arg, string, %A_Space%
 
Line 356:
out .= arg%A_Index% "`n"
MsgBox,% out ? out:"No non-blank arguments were passed."
}</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 363:
This f() can accept 0 to 3 arguments.
 
<langsyntaxhighlight lang="awk">function f(a, b, c){
if (a != "") print a
if (b != "") print b
Line 373:
print "[2 args]"; f(1, 2)
print "[3 args]"; f(1, 2, 3)
}</langsyntaxhighlight>
 
<pre>[1 arg]
Line 387:
This f() can also accept array elements. This works because any missing array elements default to "", so f() ignores them.
 
<langsyntaxhighlight lang="awk">function f(a, b, c) {
if (a != "") print a
if (b != "") print b
Line 399:
# Pass to f().
f(ary[1], ary[2], ary[3])
}</langsyntaxhighlight>
 
<pre>Line 1
Line 406:
Functions like f() can take only a few arguments. To accept more arguments, or to accept "" as an argument, the function must take an array, and the caller must bundle its arguments into an array. This g() accepts 0 or more arguments in an array.
 
<langsyntaxhighlight lang="awk">function g(len, ary, i) {
for (i = 1; i <= len; i++) print ary[i];
}
Line 414:
g(c, a) # Pass a[1] = "Line 1", a[4] = "", ...
 
}</langsyntaxhighlight>
 
<pre>Line 1
Line 425:
Variable argument lists are defined with the keyword '''VAR''', and are passed as an indexed array of strings. The number of elements is specified by a SIZE parameter. ''Arguments to functions could also simply be indexed or associative arrays or multiple element delimited strings.''
 
<langsyntaxhighlight lang="freebasic">' Variadic functions
OPTION BASE 1
SUB demo (VAR arg$ SIZE argc)
Line 440:
demo("abc")
' Three arguments
demo("123", "456", "789")</langsyntaxhighlight>
 
{{out}}
Line 466:
The parameter list does not pass information about parameter type. If necessary, the type information has to be passed for example in the first parameter.
C calling convention has to be used (with keyword cdecl).
<langsyntaxhighlight lang="freebasic">SUB printAll cdecl (count As Integer, ... )
DIM arg AS Any Ptr
DIM i AS Integer
Line 477:
END SUB
 
printAll 3, 3.1415, 1.4142, 2.71828</langsyntaxhighlight>
For some reason, I was not able to get a Strings version of the above to work.
==={{header|FreeBASIC}}===
String version
<langsyntaxhighlight lang="freebasic">' version 15-09-2015
' compile with: fbc -s console
 
Line 519:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>only the last example shown
Line 533:
The existence of more parameters as well as the type of each parameter can be checked with function ITEM().
 
<langsyntaxhighlight lang="zxbasic">100 DEF PROC printAll DATA
110 DO UNTIL ITEM()=0
120 IF ITEM()=1 THEN
Line 545:
 
200 printAll 3.1415, 1.4142, 2.71828
210 printAll "Mary", "had", "a", "little", "lamb",</langsyntaxhighlight>
 
The code above is for Beta BASIC. There is a small difference between Beta BASIC and SAM BASIC.
Line 553:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
@echo off
 
Line 567:
:: Note: if _variadicfunc was called from cmd.exe with arguments parsed to it, it would only need to contain:
:: @for %%i in (%*) do echo %%i
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 581:
:c) the first element in the array specifies the number of arguments.
 
<langsyntaxhighlight lang="bc">/* Version a */
define f(a[], l) {
auto i
Line 598:
for (i = 1; i <= a[0]; i++) a[i]
}</langsyntaxhighlight>
 
=={{header|BCPL}}==
 
BCPL does not have true variadic functions, however, it is explicitly legal
to pass a function the "wrong" amount of arguments. If fewer arguments are passed
than declared, the rest will remain uninitialized, if too many are passed,
the excess arguments are ignored. Additionally, it is guaranteed that the arguments will be located sequentially
in memory, starting from the first, making it possible to treat the address of the
first argument as if it is in fact an array of arguments.
 
These two facts together make it easy to declare a "variadic" function by
simply specifying a whole bunch of dummy arguments in the declaration, and then calling
the function later on with however many you happen to need. At least as many arguments as
you declare are guaranteed to make it through, though any more will not necessarily.
 
This technique is used in the standard library (this is how <code>writef</code>, the
equivalent to C's <code>printf</code>, is defined), and the book <cite>BCPL: The Language
and its Compiler</cite> by BCPL designer Martin Richards (which is as official as it gets)
explicitly introduces this technique.
 
<syntaxhighlight lang="bcpl">get "libhdr"
 
// A, B, C, etc are dummy arguments. If more are needed, more can be added.
// Eventually you will run into the compiler limit.
let foo(num, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) be
// The arguments can be indexed starting from the first one.
for i=1 to num do writef("%S*N", (@num)!i)
// You can pass as many arguments as you want. The declaration above guarantees
// that at least the first 16 arguments (including the number) will be available,
// but you certainly needn't use them all.
let start() be
foo(5, "Mary", "had", "a", "little", "lamb")</syntaxhighlight>
{{out}}
<pre>Mary
had
a
little
lamb</pre>
 
=={{header|BQN}}==
 
All BQN functions can be variadic since they allow taking lists of arbitrary length as arguments. A function can reject variadicity by defining a header to restrict the arguments to a specific length.
 
<syntaxhighlight lang="bqn">Fun1 ← •Show¨
Fun2 ← {•Show¨𝕩}
Fun3 ← { 1=≠𝕩 ? •Show 𝕩; "too many arguments " ! 𝕩}</syntaxhighlight>
 
Both <tt>Fun1</tt> and <tt>Fun2</tt> display all the values (arguments) of the lists given to them.
 
<tt>Fun3</tt> throws an error if the given argument is not a list of length 1 or not a list at all. Otherwise it displays its argument.
 
=={{header|C}}==
The ANSI C standard header <tt>stdarg.h</tt> defines macros for low-level access to the parameter stack. It does not know the number or types of these parameters; this is specified by the required initial parameter(s). For example, it could be a simple count, a terminating <tt>NULL</tt>, or a more complicated parameter specification like a printf() format string.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdarg.h>
 
Line 614 ⟶ 665:
}
 
varstrings(5, "Mary", "had", "a", "little", "lamb");</langsyntaxhighlight>
 
In C, there is no way to call a variadic function on a list of arguments constructed at runtime.
Line 626 ⟶ 677:
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">using System;
 
class Program {
Line 638 ⟶ 689:
}
}
}</langsyntaxhighlight>
 
Output:
Line 656 ⟶ 707:
{{works with|g++|4.3.0}} using option -std=c++0x
 
<langsyntaxhighlight lang="cpp">#include <iostream>
 
template<typename T>
Line 676 ⟶ 727:
std::string s = "Hello world";
print("i = ", i, " and s = \"", s, "\"\n");
}</langsyntaxhighlight>
As the example shows, variadic templates allow any type to be passed.
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">(defn foo [& args]
(doseq [a args]
(println a)))
 
(foo :bar :baz :quux)
(apply foo [:bar :baz :quux])</langsyntaxhighlight>
 
=={{header|COBOL}}==
{{works with|Micro Focus COBOL V3.2}}
<syntaxhighlight lang="text">
program-id. dsp-str is external.
data division.
Line 749 ⟶ 800:
.
end program dsp-str.
</syntaxhighlight>
</lang>
 
{{out}}
Line 763 ⟶ 814:
The [http://www.lispworks.com/documentation/HyperSpec/Body/03_dac.htm <tt>&rest</tt>] [http://www.lispworks.com/documentation/HyperSpec/Body/03_da.htm lambda list keyword] causes all remaining arguments to be bound to the following variable.
 
<langsyntaxhighlight lang="lisp">(defun example (&rest args)
(dolist (arg args)
(print arg)))
Line 770 ⟶ 821:
 
(let ((args '("Mary" "had" "a" "little" "lamb")))
(apply #'example args))</langsyntaxhighlight>
 
=={{header|Coq}}==
To define a variadic function, we build a variadic type:
 
<langsyntaxhighlight lang="coq">
Fixpoint Arity (A B: Set) (n: nat): Set := match n with
|O => B
|S n' => A -> (Arity A B n')
end.
</syntaxhighlight>
</lang>
 
This function can be used as a type, Arity A B n means <math>\underbrace{A \rightarrow \cdots \rightarrow A}_{\text{n times}} \rightarrow B</math> .
Line 788 ⟶ 839:
 
Since Arity is a type, we can compound it with itself as the destination to mean, for instance, "n naturals and 2 * n booleans" like so:
<langsyntaxhighlight lang="coq">
Definition nat_twobools (n: nat) := Arity nat (Arity bool nat (2*n)) n.
</syntaxhighlight>
</lang>
 
There is no equivalent to printf in Coq, because this function has border effects. We will then instead of printing each arguments build a list from it. <br \>
Line 799 ⟶ 850:
Finally, for the function to work, we need an accumulator of some sort
 
<langsyntaxhighlight lang="coq">
Require Import List.
Fixpoint build_list_aux {A: Set} (acc: list A) (n : nat): Arity A (list A) n := match n with
Line 805 ⟶ 856:
|S n' => fun (val: A) => build_list_aux (acc ++ (val :: nil)) n'
end.
</syntaxhighlight>
</lang>
 
Our function is then just an application of this one:
<langsyntaxhighlight lang="coq">
Definition build_list {A: Set} := build_list_aux (@nil A).
</syntaxhighlight>
</lang>
 
To call it we give it the number of argument and then the parameters we want in the list
<langsyntaxhighlight lang="coq">
Check build_list 5 1 2 5 90 42.
</syntaxhighlight>
</lang>
Which gives the result [1; 2; 5; 90; 42]
 
Line 823 ⟶ 874:
The reason for that is that the proof will be then a part of the type and computation of our function, so when we will try to compute it, Coq will be unable to unfold the opaque proof. Instead we should define our own lemmas and set their opacity to be transparent. Here are the two lemmas we will need:
 
<langsyntaxhighlight lang="coq">
Lemma transparent_plus_zero: forall n, n + O = n.
intros n; induction n.
Line 835 ⟶ 886:
- simpl; f_equal; rewrite IHn; reflexivity.
Defined.
</syntaxhighlight>
</lang>
 
Now on to the function. <br \>
Line 842 ⟶ 893:
Instead of defining a function directly, we will construct it as a proof that will be easier for us to write:
 
<langsyntaxhighlight lang="coq">
Require Import Vector.
 
Line 850 ⟶ 901:
- intros val. rewrite transparent_plus_S. apply IHn. (*Here we use the induction hypothesis. We just have to build the new accumulator*)
apply shiftin; [apply val | apply acc]. (*Shiftin adds a term at the end of a vector*)
</syntaxhighlight>
</lang>
 
As before, we can now build the full function with a null accumulator:
<langsyntaxhighlight lang="coq">
Definition build_vector {A: Set} (n: nat) := build_vector_aux n O (@nil A).
</syntaxhighlight>
</lang>
 
When we call it:
<langsyntaxhighlight lang="coq">
Require Import String.
Eval compute in build_vector 4 "Hello" "how" "are" "you".
</syntaxhighlight>
</lang>
Which gives the vector of members "Hello", "how", "are" and "you" of size 4
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
void printAll(TyArgs...)(TyArgs args) {
Line 887 ⟶ 938:
showSum1(1, 3, 50);
showSum2(1, 3, 50, 10);
}</langsyntaxhighlight>
{{out}}
<pre>4
Line 906 ⟶ 957:
 
=={{header|Delphi}}==
''See [[#Free Pascal|Free Pascal]].''
See [https://rosettacode.org/wiki/Variadic_function#Free_Pascal Free_Pascal].
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight Dyalectlang="dyalect">func printAll(args...) {
for i in args {
print(i)
Line 916 ⟶ 967:
}
 
printAll("test", "rosetta code", 123, 5.6)</langsyntaxhighlight>
 
{{out}}
Line 929 ⟶ 980:
Variadic functions in the Déjà Vu standard library generally end with <code>(</code>, <code>[</code> or <code>{</code>. For this purpose, <code>)</code>, <code>]</code> and <code>}</code> are autonyms (that is, they have a global bindings to themselves, so that <code>)</code> is the same as <code>:)</code>).
 
<langsyntaxhighlight lang="dejavu">show-all(:
while /= ) dup:
!.
drop
 
show-all( :foo "Hello" 42 [ true ] )</langsyntaxhighlight>
{{out}}
<pre>:foo
Line 947 ⟶ 998:
However, accepting any number of arguments can easily be done, as it is just a particular case of the basic mechanism for dynamic message handling:
 
<langsyntaxhighlight lang="e">def example {
match [`run`, args] {
for x in args {
Line 957 ⟶ 1,008:
example("Mary", "had", "a", "little", "lamb")
 
E.call(example, "run", ["Mary", "had", "a", "little", "lamb"])</langsyntaxhighlight>
 
 
For comparison, a plain method doing the same thing for exactly two arguments would be like this:
 
<langsyntaxhighlight lang="e">def non_example {
to run(x, y) {
println(x)
println(y)
}
}</langsyntaxhighlight>
 
or, written using the function syntax,
 
<langsyntaxhighlight lang="e">def non_example(x, y) {
println(x)
println(y)
}</langsyntaxhighlight>
 
=={{header|Ecstasy}}==
Ecstasy does not support a true variadic function (<i>a la</i> C with "<tt>...</tt>") or a syntactic sugar for the same (<i>a la</i> Java with "<tt>...</tt>" and the underlying <tt>Object[]</tt>). Instead, when a variadic call is needed, the method or function is declared with the desired array type, and the caller simply passes an array value of any length using the literal array syntax:
 
<syntaxhighlight lang="java">
module VariadicFunction {
void show(String[] strings) {
@Inject Console console;
strings.forEach(s -> console.print(s));
}
 
void run() {
show(["hello", "world"]);
 
String s1 = "not";
String s2 = "a";
String s3 = "constant";
String s4 = "literal";
show([s1, s2, s3, s4]);
}
}
</syntaxhighlight>
 
{{out}}
<pre>
hello
world
not
a
constant
literal
</pre>
 
=={{header|Egel}}==
Egel performs almost all of its work with pattern-matching anonymous functions which may match against any number of arguments. The following combinator discriminates between 2, 1, or 0 arguments; more elaborate examples are straightforward.
 
<syntaxhighlight lang="egel">
<lang Egel>
[ X Y -> "two" | X -> "one" | -> "zero" ]
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 46.1x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
Line 992 ⟶ 1,075:
printAll(params object[] list)
{
for(int i := 0,; i < list.Length,; i+=1+)
{
self.printLine(list[i])
Line 1,002 ⟶ 1,085:
{
console.printAll("test", "rosetta code", 123, 5.6r)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,014 ⟶ 1,097:
Elixir doesn't have the feature of the variable number of arguments.
However, it is possible to process as the list if putting in an argument in [].
<langsyntaxhighlight lang="elixir">defmodule RC do
def print_each( arguments ) do
Enum.each(arguments, fn x -> IO.inspect x end)
Line 1,021 ⟶ 1,104:
 
RC.print_each([1,2,3])
RC.print_each(["Mary", "had", "a", "little", "lamb"])</langsyntaxhighlight>
 
{{out}}
Line 1,039 ⟶ 1,122:
An <code>&rest</code> in the formal parameters gives all further arguments in a list, which the code can then act on in usual list ways. Fixed arguments can precede the <code>&rest</code> if desired.
 
<langsyntaxhighlight Lisplang="lisp">(defun my-print-args (&rest arg-list)
(message "there are %d argument(s)" (length arg-list))
(dolist (arg arg-list)
(message "arg is %S" arg)))
 
(my-print-args 1 2 3)</langsyntaxhighlight>
 
A function can be called with a list of arguments (and optionally fixed arguments too) with <code>apply</code>, similar to most Lisp variants.
 
<langsyntaxhighlight Lisplang="lisp">(let ((arg-list '("some thing %d %d %d" 1 2 3)))
(apply 'message arg-list))</langsyntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
^|EMal supports variadic functions in more than one way|^
fun print = void by text mode, List args do
writeLine("== " + mode + " ==")
for each var arg in args do writeLine(arg) end
end
fun printArgumentsList = void by List args
print("accepting a list", args)
end
fun printArgumentsUnchecked = void by some var args
print("unchecked variadic", args)
end
fun printArgumentsChecked = void by text subject, logic isTrue, int howMany, some text values
print("checked variadic", var[subject, isTrue, howMany, +values]) # unary plus on lists does list expansion
end
printArgumentsList(var["These are the ", true, 7, "seas", "of", "Rhye"])
printArgumentsUnchecked("These are the ", true, 7, "seas", "of", "Rhye")
printArgumentsChecked("These are the ", true, 7, "seas", "of", "Rhye")
</syntaxhighlight>
{{out}}
<pre>
== accepting a list ==
These are the
7
seas
of
Rhye
== unchecked variadic ==
These are the
7
seas
of
Rhye
== checked variadic ==
These are the
7
seas
of
Rhye
</pre>
 
=={{header|Erlang}}==
Variable amount of anything (like arguments): use a list.
<syntaxhighlight lang="erlang">
<lang Erlang>
print_each( Arguments ) -> [io:fwrite( "~p~n", [X]) || X <- Arguments].
</syntaxhighlight>
</lang>
 
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function allargs () ...
$ loop 1 to argn();
Line 1,075 ⟶ 1,203:
16
64
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">procedure print_args(sequence args)
for i = 1 to length(args) do
puts(1,args[i])
Line 1,085 ⟶ 1,213:
end procedure
 
print_args({"Mary", "had", "a", "little", "lamb"})</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Variadic function. Nigel Galloway: March 6th., 2024
open System
type X()=static member F([<ParamArray>] args: Object[]) = args|>Array.iter(printfn "%A")
X.F(23, 3.142, "Nigel", 1u, true)
</syntaxhighlight>
{{output}}
<pre>
23
3.142
Nigel
1
true
</pre>
 
=={{header|Factor}}==
Variadic functions can be created by making a word which accepts a number specifying how many data stack items to operate on.
<langsyntaxhighlight lang="factor">MACRO: variadic-print ( n -- quot ) [ print ] n*quot ;</langsyntaxhighlight>
An interactive demonstration in the listener:
<langsyntaxhighlight lang="factor">IN: scratchpad "apple" "banana" "cucumber"
 
--- Data stack:
Line 1,103 ⟶ 1,247:
 
--- Data stack:
"apple"</langsyntaxhighlight>
 
=={{header|Forth}}==
Words taking variable numbers of arguments may be written by specifying the number of parameters to operate upon as the top parameter. There are two standard words which operate this way: PICK and ROLL.
 
<langsyntaxhighlight lang="forth">: sum ( x_1 ... x_n n -- sum ) 1 ?do + loop ;
4 3 2 1 4 sum . \ 10</langsyntaxhighlight>
 
Alternatively, you can operate upon the entire parameter stack for debugging by using the word DEPTH, which returns the number of items currently on the stack.
 
<langsyntaxhighlight lang="forth">: .stack ( -- ) depth 0 ?do i pick . loop ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,121 ⟶ 1,265:
The following code shows how an optional vector argument can be used to pass a variable number of argument to a subroutine.
 
<langsyntaxhighlight lang="fortran">program varargs
 
integer, dimension(:), allocatable :: va
Line 1,153 ⟶ 1,297:
end subroutine v_func
 
end program varargs</langsyntaxhighlight>
 
=={{header|Free Pascal}}==
Note, strictly speaking the routine <tt>writeLines</tt> has exactly ''one'' parameter.
<langsyntaxhighlight lang="pascal">program variadicRoutinesDemo(input, output, stdErr);
{$mode objFPC}
 
Line 1,195 ⟶ 1,339:
begin
writeLines([42, 'is', true, #33]);
end.</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="text">42
is
TRUE
!</langsyntaxhighlight>
 
=={{header|Fōrmulæ}}==
 
In [{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Variadic_function this] page you can see the solution of this task.}}
 
'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
Fōrmulæ does not have variadic functions. However an array can be provided as argument:
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
'''Examples'''
 
Tee following function accepts a list as its unique parameter. It retrieves the list in vertical form (as a matrix of 1 column):
 
[[File:Fōrmulæ - Variadic function 01.png]]
 
[[File:Fōrmulæ - Variadic function 02.png]]
 
[[File:Fōrmulæ - Variadic function 03.png]]
 
[[File:Fōrmulæ - Variadic function 04.png]]
 
[[File:Fōrmulæ - Variadic function 05.png]]
 
With this approach we can use several parameters being lists with variable number of elements each, for example:
 
[[File:Fōrmulæ - Variadic function 06.png]]
 
[[File:Fōrmulæ - Variadic function 07.png]]
 
[[File:Fōrmulæ - Variadic function 08.png]]
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">void local fn Function1( count as long, ... )
va_list ap
long value
 
va_start( ap, count )
while ( count )
value = fn va_argLong( ap )
printf @"%ld",value
count--
wend
 
va_end( ap )
end fn
 
void local fn Function2( obj as CFTypeRef, ... )
va_list ap
 
va_start( ap, obj )
while ( obj )
printf @"%@",obj
obj = fn va_argObj(ap)
wend
 
va_end( ap )
end fn
 
window 1
 
// params: num of args, 1st arg, 2nd arg, etc.
fn Function1( 3, 987, 654, 321 )
 
print
 
// params: 1st arg, 2nd arg, ..., NULL
fn Function2( @"One", @"Two", @"Three", @"O'Leary", NULL )
 
HandleEvents</syntaxhighlight>
{{Out}}
<pre>987
654
321
 
One
Two
Three
O'Leary</pre>
 
=={{header|Go}}==
A variadic function in Go has a <code>...</code> prefix on the type of the final parameter. [https://golang.org/ref/spec#Function_types (spec, Function types)]
 
<langsyntaxhighlight lang="go">func printAll(things ... string) {
// it's as if you declared "things" as a []string, containing all the arguments
for _, x := range things {
fmt.Println(x)
}
}</langsyntaxhighlight>
 
If you wish to supply an argument list to a variadic function at runtime, you can do this by adding a <code>...</code> ''after'' a slice argument:
<langsyntaxhighlight lang="go">args := []string{"foo", "bar"}
printAll(args...)</langsyntaxhighlight>
 
=={{header|Golo}}==
<langsyntaxhighlight lang="golo">#!/usr/bin/env golosh
----
This module demonstrates variadic functions.
Line 1,248 ⟶ 1,462:
# to call a variadic function with an array we use the unary function
unary(^varargsFunc)(args)
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def printAll( Object[] args) { args.each{ arg -> println arg } }
 
printAll(1, 2, "three", ["3", "4"])</langsyntaxhighlight>
 
Sample output:
Line 1,263 ⟶ 1,477:
=={{header|Haskell}}==
You can use some fancy recursive type-class instancing to make a function that takes an unlimited number of arguments. This is how, for example, printf works in Haskell.
<langsyntaxhighlight lang="haskell">class PrintAllType t where
process :: [String] -> t
 
Line 1,279 ⟶ 1,493:
main = do printAll 5 "Mary" "had" "a" "little" "lamb"
printAll 4 3 5
printAll "Rosetta" "Code" "Is" "Awesome!"</langsyntaxhighlight>
So here we created a type class specially for the use of this variable-argument function. The type class specifies a function, which takes as an argument some kind of accumulated state of the arguments so far, and returns the type of the type class. Here I chose to accumulate a list of the string representations of each of the arguments; this is not the only way to do it; for example, you could choose to print them directly and just accumulate the IO monad.
 
We need two kinds of instances of this type class. There is the "base case" instance, which has the type that can be thought of as the "return type" of the vararg function. It describes what to do when we are "done" with our arguments. Here we just take the accumulated list of strings and print them, one per line.
We actually wanted to use "IO ()" instead of "IO a"; but since you can't instance just a specialization like "IO ()", we used "IO a" but return "undefined" to make sure nobody uses it. Or we can use GADTs pragma and constraint in instance like this :
<langsyntaxhighlight lang="haskell">{-# LANGUAGE GADTs #-}
...
 
Line 1,290 ⟶ 1,504:
process args = do mapM_ putStrLn args
 
...</langsyntaxhighlight>
 
You can have multiple base case instances; for example, you might want an instances that returns the result as a string instead of printing it. This is how "printf" in Haskell can either print to stdout or print to string (like sprintf in other languages), depending on the type of its context.
Line 1,299 ⟶ 1,513:
varargs.icn
 
<langsyntaxhighlight lang="icon">procedure main ()
varargs("some", "extra", "args")
write()
Line 1,307 ⟶ 1,521:
procedure varargs(args[])
every write(!args)
end</langsyntaxhighlight>
 
Using it
Line 1,319 ⟶ 1,533:
c
d</pre>
 
=={{header|Insitux}}==
<syntaxhighlight lang="insitux">(function f
(print (join "\n" args)))
 
(f 1 2 3 4)</syntaxhighlight>
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">printAll := method(call message arguments foreach(println))</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,329 ⟶ 1,549:
For example:
 
<langsyntaxhighlight Jlang="j"> A=:2
B=:3
C=:5
sum=:+/
sum 1,A,B,4,C
15</langsyntaxhighlight>
 
That said, J expects that members of lists all use the same kind of machine representation. If you want both character literals and numbers for arguments, or if you want arrays with different dimensions, each argument must be put into a box, and the function is responsible for dealing with the packing material.
 
<langsyntaxhighlight Jlang="j"> commaAnd=: [: ; (<' and ') _2} ::] 1 }.&, (<', ') ,. ":each
commaAnd 'dog';A;B;'cat';C
dog, 2, 3, cat and 5</langsyntaxhighlight>
 
To print each argument on its own line, we would typically map <code>echo</code> over the arguments (in this example, the contents of each box):
 
<syntaxhighlight lang="j"> echo&>'dog';A;B;'cat';C
dog
2
3
cat
5</syntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
Using <tt>...</tt> after the type of argument will take in any number of arguments and put them all in one array of the given type with the given name.
<langsyntaxhighlight lang="java5">public static void printAll(Object... things){
// "things" is an Object[]
for(Object i:things){
System.out.println(i);
}
}</langsyntaxhighlight>
This function can be called with any number of arguments:
<langsyntaxhighlight lang="java5">printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!");</langsyntaxhighlight>
 
Or with an array directly (the array must have the appropriate array type; i.e. if it is <tt>String...</tt>, then you need to pass a <tt>String[]</tt>):
<langsyntaxhighlight lang="java5">Object[] args = {"Rosetta", "Code", "Is", "Awesome!"};
printAll(args);</langsyntaxhighlight>
 
But not with both (in this case the array is considered as just one of two arguments, and not expanded):
<langsyntaxhighlight lang="java5">Object[] args = {"Rosetta", "Code", "Is", "Awesome,"};
printAll(args, "Dude!");//does not print "Rosetta Code Is Awesome, Dude!"
//instead prints the type and hashcode for args followed by "Dude!"</langsyntaxhighlight>
 
In some rare cases, you may want to pass an array as just a single argument, but doing it directly would expand it to be the entire argument. In this case, you need to cast the array to <tt>Object</tt> (all arrays are objects) so the compiler doesn't know it's an array anymore.
<syntaxhighlight lang ="java5">printAll((Object)args);</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
The [https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Functions/arguments <code>arguments</code>] special variable, when used inside a function, contains an array of all the arguments passed to that function.
<langsyntaxhighlight lang="javascript">function printAll() {
for (var i=0; i<arguments.length; i++)
print(arguments[i])
Line 1,377 ⟶ 1,606:
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!");</langsyntaxhighlight>
The <code><var>function</var>.arguments</code> property is equivalent to the <code>arguments</code> variable above, but is deprecated.
 
You can use the <tt>apply</tt> method of a function to apply it to a list of arguments:
<langsyntaxhighlight lang="javascript">args = ["Rosetta", "Code", "Is", "Awesome!"]
printAll.apply(null, args)</langsyntaxhighlight>
 
===ECMAScript 2015 (ES6) variants===
The newest version of ECMAScript added fat arrow function expression syntax, rest arguments and the spread operator. These make writing something like this easy. Of course, a better version might use Array.prototype.map, but here we have a variant that works on variadic arguments:
<langsyntaxhighlight lang="javascript">let
fix = // Variant of the applicative order Y combinator
f => (f => f(f))(g => f((...a) => g(g)(...a))),
Line 1,415 ⟶ 1,644:
// 13
// 14
</syntaxhighlight>
</lang>
 
Or, less ambitiously:
 
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,430 ⟶ 1,659:
 
return printAll(1, 2, 3, 2 + 2, "five", 6);
})();</langsyntaxhighlight>
 
{{Out}}
Line 1,446 ⟶ 1,675:
 
The first task requirement can in effect be accomplished using a 0-arity function defined as follows:
<syntaxhighlight lang ="jq">def demo: .[];</langsyntaxhighlight>
 
The parameters would be presented to <code>demo</code> in the form of an array. For example, given an array, args, constructed at runtime, the second task requirement can be accomplished by calling:
<syntaxhighlight lang ="jq">args | demo</langsyntaxhighlight>
For example:
<langsyntaxhighlight lang="jq">["cheese"] + [3.14] + [[range(0;3)]] | demo</langsyntaxhighlight>
produces:
<langsyntaxhighlight lang="sh">"cheese"
3.14
[0,1,2]</langsyntaxhighlight>
 
'''Variadic Function Names''':
Line 1,462 ⟶ 1,691:
 
In recent releases of jq (after version 1.4), function names are variadic in the sense that, if f is a function name, then f/n can be defined for multiple values of n. However, jq does not support the programmatic construction of function calls, and if a function is called with an undefined name/arity combination, then an error will be raised.
<syntaxhighlight lang="jq">
<lang jq>
# arity-0:
def f: "I have no arguments";
Line 1,475 ⟶ 1,704:
 
# Example:
f, f(1), f(2;3), f(4;5;6)</langsyntaxhighlight>
produces:
<langsyntaxhighlight lang="sh">1
2
3
4
5
6</langsyntaxhighlight>
 
=={{header|Julia}}==
Putting <code>...</code> after the last argument in a function definition makes it variadic (any number of arguments are passed as a tuple):
<langsyntaxhighlight lang="julia">
julia> print_each(X...) = for x in X; println(x); end
 
Line 1,493 ⟶ 1,722:
hello
23.4
</syntaxhighlight>
</lang>
Conversely, when <code>...</code> is appended to an array (or other iterable object) passed to the function, the array is converted to a sequence of arguments:
<langsyntaxhighlight lang="julia">
julia> args = [ "first", (1,2,17), "last" ]
3-element Array{Any,1}:
Line 1,506 ⟶ 1,735:
(1,2,17)
last
</syntaxhighlight>
</lang>
 
=={{header|Klingphix}}==
<langsyntaxhighlight Klingphixlang="klingphix">:varfunc
1 tolist flatten
len [
Line 1,520 ⟶ 1,749:
stklen [split varfunc nl] if
 
nl "End " input</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1
 
fun variadic(vararg va: String) {
Line 1,539 ⟶ 1,768:
println()
variadic(*va)
}</langsyntaxhighlight>
Sample input/output:
{{out}}
Line 1,559 ⟶ 1,788:
</pre>
 
=={{header|LambdatalkKsh}}==
<syntaxhighlight lang="ksh">
Lambdas are de facto variadic in lambdatalk
#!/bin/ksh
<lang scheme>
{def foo
{lambda {:s}
{if {S.empty? {S.rest :s}}
then {br}{S.first :s}
else {br}{S.first :s} {foo {S.rest :s}}}}}
 
# Variadic function
{foo hello brave new world} ->
hello
brave
new
world
 
# # Variables:
{foo {S.serie 1 10}} ->
#
1
typeset -a arr=( 0 2 4 6 8 )
 
# # Functions:
#
function _variadic {
while [[ -n $1 ]]; do
print $1
shift
done
}
 
######
# main #
######
 
_variadic Mary had a little lamb
echo
_variadic ${arr[@]}</syntaxhighlight>
{{out}}<pre>
Mary
had
a
little
lamb
 
0
2
3
4
5
6
8</pre>
7
 
8
=={{header|Lambdatalk}}==
9
 
10
Lambdas are de facto variadic in lambdatalk
 
<syntaxhighlight lang="scheme">
 
{def foo
{lambda {:s} // :s will get any sequence of words
{S.first :s}
{if {S.empty? {S.rest :s}} then else {foo {S.rest :s}}}}}
-> foo
 
{foo hello brave new world}
-> hello brave new world
 
{foo {S.serie 1 10}}
-> 1 2 3 4 5 6 7 8 9 10
</syntaxhighlight>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
fp.printAll = (&values...) -> {
fn.arrayForEach(&values, fn.println)
}
 
fp.printAll(1, 2, 3)
# 1
# 2
# 3
 
fp.printAll() # No output
 
fp.printAll(abc, def, xyz)
# abc
# def
# xyz
 
# Array un-packing
&arr $= [1, abc, xyz, 42.42f]
fp.printAll(&arr...)
# 1
# abc
# xyz
# 42.42
 
fp.printAll(&arr..., last)
# 1
# abc
# xyz
# 42.42
# last
 
fp.printAll(first, &arr...)
# first
# 1
# abc
# xyz
# 42.42
</syntaxhighlight>
Solution with the use of arguments auto-pack operator and combinator function:
<syntaxhighlight lang="lang">
fp.printAllComb $= -|fn.combC(fn.arrayForEach, fn.println)
 
fp.printAllComb(42, 2, abc)
# 42
# 2
# abc
 
fp.printAllComb() # No output
 
&arr $= [1, abc, xyz, 42.42f]
</lang>
fp.printAllComb(&arr...)
# 1
# abc
# xyz
# 42.42
</syntaxhighlight>
 
=={{header|Lasso}}==
A Lasso method parameter name can prefixed by "..." to specify a variable number of parameters, which are made available as a staticarray. If no name is specified, the staticarray will be named "rest".
<langsyntaxhighlight lang="lasso">define printArgs(...items) => stdoutnl(#items)
define printEachArg(...) => with i in #rest do stdoutnl(#i)
 
printArgs('a', 2, (:3))
printEachArg('a', 2, (:3))</langsyntaxhighlight>
To expand an existing list, pass it to the method using invocation syntax.
<langsyntaxhighlight lang="lasso">local(args = (:"Rosetta", "Code", "Is", "Awesome!"))
printEachArg(:#args)</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="lasso">staticarray(a, 2, staticarray(3))
a
2
Line 1,606 ⟶ 1,923:
Code
Is
Awesome!</langsyntaxhighlight>
 
=={{header|Logo}}==
Line 1,615 ⟶ 1,932:
# an optional "rest" input (a list containing a colon prefixed word, set to the list of remaining arguments)
# ...with an optional default arity (a number)
<langsyntaxhighlight lang="logo">to varargs [:args]
foreach :args [print ?]
end
 
(varargs "Mary "had "a "little "lamb)
apply "varargs [Mary had a little lamb]</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 1,626 ⟶ 1,943:
The generic syntax for defining a variadic function is appending an ellipsis to the list of arguments:
 
<langsyntaxhighlight lang="lua">function varar(...)
for i, v in ipairs{...} do print(v) end
end</langsyntaxhighlight>
 
It is then used like so:
 
<langsyntaxhighlight lang="lua">varar(1, "bla", 5, "end");</langsyntaxhighlight>
{{out}}
<pre>1
Line 1,641 ⟶ 1,958:
When used with runtime arrays, the unpack function must be called on the array, otherwise the array itself will be used as the only argument:
 
<langsyntaxhighlight lang="lua">local runtime_array = {1, "bla", 5, "end"};
 
varar(unpack(runtime_array));</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,657 ⟶ 1,974:
Module's have stack too, but calling a module from module pass the same stack. This hold if we call function using Call statement.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
\\ Works for numbers and strings (letters in M2000)
Line 1,696 ⟶ 2,013:
}
Checkit2
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">define(`showN',
`ifelse($1,0,`',`$2
$0(decr($1),shift(shift($@)))')')dnl
Line 1,708 ⟶ 2,025:
define(`x',`1,2')
define(`y',`,3,4,5')
showargs(x`'y)</langsyntaxhighlight>
 
Output (with tracing):
Line 1,727 ⟶ 2,044:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Function that takes 0 to infinite arguments and prints the arguments:
<langsyntaxhighlight Mathematicalang="mathematica">ShowMultiArg[x___] := Do[Print[i], {i, {x}}]</langsyntaxhighlight>
Example:
<langsyntaxhighlight Mathematicalang="mathematica">ShowMultiArg[]
ShowMultiArg[a, b, c]
ShowMultiArg[5, 3, 1]</langsyntaxhighlight>
gives back:
<langsyntaxhighlight Mathematicalang="mathematica">[nothing]
 
a
Line 1,743 ⟶ 2,060:
5
3
1</langsyntaxhighlight>
In general Mathematica supports patterns in functions, mostly represented by the blanks and sequences: _, __ and ___ . With those you can create functions with variable type and number of arguments.
 
Line 1,749 ⟶ 2,066:
In MATLAB, the keyword "varargin" in the argument list of a function denotes that function as a variadic function. This keyword must come last in the list of arguments. "varargin" is actually a cell-array that assigns a comma separated list of input arguments as elements in the list. You can access each of these elements like you would any normal cell array.
 
<langsyntaxhighlight MATLABlang="matlab">function variadicFunction(varargin)
 
for i = (1:numel(varargin))
Line 1,755 ⟶ 2,072:
end
end</langsyntaxhighlight>
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> variadicFunction(1,2,3,4,'cat')
1
 
Line 1,767 ⟶ 2,084:
4
 
cat</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">show([L]) := block([n], n: length(L), for i from 1 thru n do disp(L[i]))$
 
show(1, 2, 3, 4);
Line 1,779 ⟶ 2,096:
disp(1, 2, 3, 4);
 
apply(disp, [1, 2, 3, 4]);</langsyntaxhighlight>
 
=={{header|Metafont}}==
Line 1,785 ⟶ 2,102:
Variable number of arguments to a macro can be done using the <tt>text</tt> keyword identifying the kind of argument to the macro. In this way, each argument can be of any kind (here, as example, I show all the primitive types that Metafont knows)
 
<langsyntaxhighlight lang="metafont">ddefdef print_arg(text t) =
for x = t:
if unknown x: message "unknown value"
Line 1,798 ⟶ 2,115:
 
print_arg("hello", x, 12, fullcircle, currentpicture, down, identity, false, pencircle);
end</langsyntaxhighlight>
 
=={{header|Modula-3}}==
Modula-3 provides the built ins <tt>FIRST</tt> and <tt>LAST</tt>, which can be used with <tt>FOR</tt> loops to cycle over all elements of an array. This, combined with open arrays allows Modula-3 to simulate variadic functions.
<langsyntaxhighlight lang="modula3">MODULE Varargs EXPORTS Main;
 
IMPORT IO;
Line 1,817 ⟶ 2,134:
BEGIN
Variable(strings);
END Varargs.</langsyntaxhighlight>
Output:
<pre>
Line 1,827 ⟶ 2,144:
</pre>
Things get more complicated if you want to mix types:
<langsyntaxhighlight lang="modula3">MODULE Varargs EXPORTS Main;
 
IMPORT IO, Fmt;
Line 1,852 ⟶ 2,169:
strings^ := "Rosetta"; ints^ := 1; reals^ := 3.1415;
Variable(refarr);
END Varargs.</langsyntaxhighlight>
Output:
<pre>
Line 1,863 ⟶ 2,180:
{{trans|C#}}
Like C#, Nemerle uses the <tt>params</tt> keyword to specify that arguments are collected into an array.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 1,877 ⟶ 2,194:
PrintAll("test", "rosetta code", 123, 5.6, DateTime.Now);
}
}</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc print(xs: varargs[string, `$`]) =
for x in xs:
echo x</langsyntaxhighlight>
The function can be called with any number of arguments and the argument list can be constructed at runtime:
<langsyntaxhighlight lang="nim">print(12, "Rosetta", "Code", 15.54321)
 
print 12, "Rosetta", "Code", 15.54321, "is", "awesome!"
 
let args = @["12", "Rosetta", "Code", "15.54321"]
print(args)</langsyntaxhighlight>
 
=={{header|Objective-C}}==
Objective-C uses the same varargs functionality as C. Like C, it has no way of knowing the number or types of the arguments. When the arguments are all objects, the convention is that, if the number of arguments is undetermined, then the list must be "terminated" with <code>nil</code>. Functions that follow this convention include the constructors of data structures that take an undetermined number of elements, like <code>[NSArray arrayWithObjects:...]</code>.
 
<langsyntaxhighlight lang="objc">#include <stdarg.h>
 
void logObjects(id firstObject, ...) // <-- there is always at least one arg, "nil", so this is valid, even for "empty" list
Line 1,908 ⟶ 2,225:
// This function can be called with any number or type of objects, as long as you terminate it with "nil":
logObjects(@"Rosetta", @"Code", @"Is", @"Awesome!", nil);
logObjects(@4, @3, @"foo", nil);</langsyntaxhighlight>
 
=={{header|OCaml}}==
OCaml's strong type system makes writing variadic functions complex, as there is no <code>'a... -> 'b</code> type.
In general, writing a function that takes a list as argument is the best practice :
<syntaxhighlight lang="ocaml">let rec print = function
| [] -> ()
| x :: xs -> print_endline x; print xs
 
(* Or better yet *)
let print = List.iter print_endline
 
let () =
print [];
print ["hello"; "world!"]</syntaxhighlight>
 
If you really need a true variadic function, there are a few ways to make it work.
The first is to specify the function's type with its first argument using a generalized algebraic data type (GADT) :
 
<syntaxhighlight lang="ocaml">type 'a variadic =
| Z : unit variadic
| S : 'a variadic -> (string -> 'a) variadic
 
let rec print : type a. a variadic -> a = function
| Z -> ()
| S v -> fun x -> Format.printf "%s\n" x; print v
 
let () =
print Z; (* no arguments *)
print (S Z) "hello"; (* one argument *)
print (S (S (S Z))) "how" "are" "you" (* three arguments *)</syntaxhighlight>
 
You can even specify different types with more GADT constructors:
<syntaxhighlight lang="ocaml">type 'a variadic =
| Z : unit variadic
| U : 'a variadic -> (unit -> 'a) variadic
| S : 'a variadic -> (string -> 'a) variadic
| I : 'a variadic -> (int -> 'a) variadic
| F : 'a variadic -> (float -> 'a) variadic
(* Printing of a general type, takes pretty printer as argument *)
| G : 'a variadic -> (('t -> unit) -> 't -> 'a) variadic
| L : 'a variadic -> (('t -> unit) -> 't list -> 'a) variadic
 
let rec print : type a. a variadic -> a = function
| Z -> ()
| U v -> fun () -> Format.printf "()\n"; print v
| S v -> fun x -> Format.printf "%s\n" x; print v
| I v -> fun x -> Format.printf "%d\n" x; print v
| F v -> fun x -> Format.printf "%f\n" x; print v
| G v -> fun pp x -> pp x; print v
| L v -> fun pp x -> List.iter pp x; print v
 
let () =
print (S (I (S Z))) "I am " 5 "Years old";
print (S (I (S (L (S Z))))) "I have " 3 " siblings aged " (print (I Z)) [1;3;7]</syntaxhighlight>
 
This is what the <code>Format.printf</code> functions do. The only difference is that the compiler constructs the GADT term from the given format string. This is why you can only call them with an explicit string argument, and not a variable of type string.
 
Another method uses continuation passing style (CPS) :
<syntaxhighlight lang="ocaml">let print f = f ()
let arg value () cont = cont (Format.printf "%s\n" value)
let stop a = a
 
let () =
print stop;
print (arg "hello") (arg "there") stop;
 
(* use a prefix operator for arg *)
let (!) = arg
 
let () =
print !"hello" !"hi" !"its" !"me" stop</syntaxhighlight>
 
This isn't really a variadic function though, it's a hack that looks like one. The work is being done in the <code>arg</code> function, not <code>print</code>.
 
Other example (sequential composition or Lisp-like <code>apply</code>).
<syntaxhighlight lang="ocaml">type ('f,'g) t =
| Z : ('f,'f) t
| S : 'a -> (('a -> 'f), ('f,'g) t -> 'g) t
 
let rec apply: type f g. f -> (f,g) t -> g =
fun k t -> match t with
| Z -> k (* type g = f *)
| S x -> apply (k x) (* type g = (f,g) t -> g *)
 
let (!) x = S x (* prefix *)
 
(* top level *)
# apply List.map !(fun x -> x+1) ![1;2;3] Z</syntaxhighlight>
 
=={{header|Oforth}}==
Line 1,915 ⟶ 2,320:
 
For instance :
<langsyntaxhighlight Oforthlang="oforth">: sumNum(n) | i | 0 n loop: i [ + ] ;</langsyntaxhighlight>
 
{{out}}
Line 1,929 ⟶ 2,334:
=={{header|Oz}}==
This is only possible for methods, not for functions/procedures.
<langsyntaxhighlight lang="oz">declare
class Demo from BaseObject
meth test(...)=Msg
Line 1,940 ⟶ 2,345:
in
{D test(1 2 3 4)}
{D Constructed}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 1,946 ⟶ 2,351:
 
{{Works with|PARI/GP|2.8+}}
<langsyntaxhighlight lang="parigp">f(a[..])=for(i=1,#a,print(a[i]))</langsyntaxhighlight>
 
{{Works with|PARI/GP|2.8.1+}}
<syntaxhighlight lang ="parigp">call(f, v)</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,959 ⟶ 2,364:
Functions in Perl 5 don't have argument lists. All arguments are stored in the array <tt>@_</tt> anyway, so there is variable arguments by default.
 
<langsyntaxhighlight lang="perl">sub print_all {
foreach (@_) {
print "$_\n";
}
}</langsyntaxhighlight>
 
This function can be called with any number of arguments:
<langsyntaxhighlight lang="perl">print_all(4, 3, 5, 6, 4, 3);
print_all(4, 3, 5);
print_all("Rosetta", "Code", "Is", "Awesome!");</langsyntaxhighlight>
 
Since lists are flattened when placed in a list context, you can just pass an array in as an argument and all its elements will become separate arguments:
<langsyntaxhighlight lang="perl">@args = ("Rosetta", "Code", "Is", "Awesome!");
print_all(@args);</langsyntaxhighlight>
 
Introduced '''experimentally''' in 5.20.0, subroutines can have signatures when the feature is turned on:
<langsyntaxhighlight lang="perl">use 5.020;
use experimental 'signatures';</langsyntaxhighlight>
Perl policy states that all bets are off with experimental features—their behavior is subject to change at any time, and they may even be removed completely (''this feature will most likely stay in, but expect changes in the future that will break any scripts written using it as it stands in 5.20.1'').
 
Functions can be declared with fixed arity:
<langsyntaxhighlight lang="perl">sub print ($x, $y) {
say $x, "\n", $y;
}</langsyntaxhighlight>
 
But this can easily be converted to a variadic function with a slurpy parameter:
<langsyntaxhighlight lang="perl">sub print_many ($first, $second, @rest) {
say "First: $first\n"
."Second: $second\n"
."And the rest: "
. join("\n", @rest);
}</langsyntaxhighlight>
It is valid for the @rest array to be empty, so this is also an optional parameter (see [[Optional parameters]]).
 
Line 1,996 ⟶ 2,401:
{{libheader|Phix/basics}}
Copy of [[Variadic_function#Euphoria|Euphoria]]. The argument to print_args could be anything constructed at runtime. You can also specify optional parameters, simply by specifying a default value. Any non-optional arguments must be grouped together at the start.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">print_args</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">args</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">args</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
Line 2,003 ⟶ 2,408:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">print_args</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"Mary"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"had"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"a"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"little"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"lamb"</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def varfunc
1 tolist flatten
len for
Line 2,014 ⟶ 2,419:
 
 
"Mary" "had" "a" "little" "lamb" 5 tolist varfunc</langsyntaxhighlight>
 
=={{header|PHP}}==
PHP 4 and above supports varargs. You can deal with the argument list using the <tt>func_num_args()</tt>, <tt>func_get_arg()</tt>, and <tt>func_get_args()</tt> functions.
<langsyntaxhighlight lang="php"><?php
function printAll() {
foreach (func_get_args() as $x) // first way
Line 2,030 ⟶ 2,435:
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!");
?></langsyntaxhighlight>
 
You can use the <tt>call_user_func_array</tt> function to apply it to a list of arguments:
<langsyntaxhighlight lang="php"><?php
$args = array("Rosetta", "Code", "Is", "Awesome!");
call_user_func_array('printAll', $args);
?></langsyntaxhighlight>
 
{{works with|PHP|5.6+}}
You can receive variable arguments in a list by having a parameter preceded by <tt>...</tt>:
<langsyntaxhighlight lang="php"><?php
function printAll(...$things) {
foreach ($things as $x)
Line 2,048 ⟶ 2,453:
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!");
?></langsyntaxhighlight>
 
You can use the same <tt>...</tt> syntax to supply a list of arguments to a function:
<langsyntaxhighlight lang="php"><?php
$args = ["Rosetta", "Code", "Is", "Awesome!"];
printAll(...$args);
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Line 2,063 ⟶ 2,468:
'[http://software-lab.de/doc/refA.html#arg arg]' and
'[http://software-lab.de/doc/refR.html#rest rest]' functions.
<langsyntaxhighlight PicoLisplang="picolisp">(de varargs @
(while (args)
(println (next)) ) )</langsyntaxhighlight>
The '@' operator may be used in combination with normal parameters:
<langsyntaxhighlight PicoLisplang="picolisp">(de varargs (Arg1 Arg2 . @)
(println Arg1)
(println Arg2)
(while (args)
(println (next)) ) )</langsyntaxhighlight>
It is called like any other function
<langsyntaxhighlight PicoLisplang="picolisp">(varargs 'a 123 '(d e f) "hello")</langsyntaxhighlight>
also by possibly applying it to a ready-made list
<langsyntaxhighlight PicoLisplang="picolisp">(apply varargs '(a 123 (d e f) "hello"))</langsyntaxhighlight>
Output in all cases:
<pre>a
Line 2,083 ⟶ 2,488:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">/* PL/I permits optional arguments, but not an infinitely varying */
/* argument list: */
s: procedure (a, b, c, d);
Line 2,091 ⟶ 2,496:
if ^omitted(c) then put skip list (c);
if ^omitted(d) then put skip list (d);
end s;</langsyntaxhighlight>
 
=={{header|Plain English}}==
The only built-in imperative in Plain English that has variadic arguments is the 'call' imperative:
<syntaxhighlight lang="text">Call [dll name] [dll function] with [a value] and [another value].</syntaxhighlight>
The number of arguments used in the statement varies on the number of arguments needed by the DLL function. Variadic functions cannot be user-defined.
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function print_all {
foreach ($x in $args) {
Write-Host $x
}
}</langsyntaxhighlight>
Normal usage of the function just uses all arguments one after another:
<syntaxhighlight lang ="powershell">print_all 1 2 'foo'</langsyntaxhighlight>
In PowerShell v1 there was no elegant way of using an array of objects as arguments to a function which leads to the following idiom:
<langsyntaxhighlight lang="powershell">$array = 1,2,'foo'
Invoke-Expression "& print_all $array"</langsyntaxhighlight>
PowerShell v2 introduced the splat operator which makes this easier:
 
{{works with|PowerShell|2}}
<syntaxhighlight lang ="powershell">print_all @array</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 2,130 ⟶ 2,540:
lists are often used instead of comma-lists to handle situations where
vararg-behavior is wanted. For example:
<langsyntaxhighlight lang="prolog">printAll( List ) :- forall( member(X,List), (write(X), nl)).
</syntaxhighlight>
</lang>
To handle more esoteric situations, we could define a higher-order predicate to handle terms of arbitrary arity, e.g.
<langsyntaxhighlight lang="prolog">
execute( Term ) :-
Term =.. [F | Args],
forall( member(X,Args), (G =.. [F,X], G, nl) ).
</syntaxhighlight>
</lang>
<pre>
?- execute( write(1,2,3) ).
Line 2,148 ⟶ 2,558:
Putting <tt>*</tt> before an argument will take in any number of arguments and put them all in a tuple with the given name.
 
<langsyntaxhighlight lang="python">def print_all(*things):
for x in things:
print x</langsyntaxhighlight>
 
This function can be called with any number of arguments:
<langsyntaxhighlight lang="python">print_all(4, 3, 5, 6, 4, 3)
print_all(4, 3, 5)
print_all("Rosetta", "Code", "Is", "Awesome!")</langsyntaxhighlight>
 
You can use the same "*" syntax to apply the function to an existing list of arguments:
<langsyntaxhighlight lang="python">args = ["Rosetta", "Code", "Is", "Awesome!"]
print_all(*args)</langsyntaxhighlight>
 
===Keyword arguments ===
Python also has keyword arguments were you can add arbitrary ''func('''''keyword1=value1, keyword2=value2 ...''''')'' keyword-value pairs when calling a function.
This example shows both keyword arguments and positional arguments. The two calls to the function are equivalent. '''*alist''' spreads the members of the list to create positional arguments, and '''**adict''' does similar for the keyword/value pairs from the dictionary.
<langsyntaxhighlight lang="python">>>> def printargs(*positionalargs, **keywordargs):
print "POSITIONAL ARGS:\n " + "\n ".join(repr(x) for x in positionalargs)
print "KEYWORD ARGS:\n " + '\n '.join(
Line 2,188 ⟶ 2,598:
'fee' = 'fi'
'fo' = 'fum'
>>></langsyntaxhighlight>
 
See the Python entry in [[Named_Arguments#Python|Named Arguments]] for a more comprehensive description of Python function parameters and call arguments.
Line 2,197 ⟶ 2,607:
puts all arguments into a list.
 
<syntaxhighlight lang="qi">
<lang qi>
(define varargs-func
A -> (print A))
Line 2,206 ⟶ 2,616:
 
(sugar in varargs 1)
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
Line 2,214 ⟶ 2,624:
(<code>oats</code>: "'''o'''ne '''a'''nd '''t'''he '''s'''ame" compares the ''identity'' of two items, ensuring that <code>marker</code> is uniquely identified.)
 
<langsyntaxhighlight Quackerylang="quackery">[ pack witheach
[ echo$ cr ] ] is counted-echo$ ( $ ... n --> )
 
Line 2,231 ⟶ 2,641:
$ "this" $ "is" $ "a" $ "formica" $ "table" 5 counted-echo$
cr
marker $ "green" $ "is" $ "its" $ "colour" markered-echo$</langsyntaxhighlight>
 
{{out}}
Line 2,249 ⟶ 2,659:
=={{header|R}}==
This first function, almost completes the task, but the formatting isn't quite as specified.
<langsyntaxhighlight lang="rsplus"> printallargs1 <- function(...) list(...)
printallargs1(1:5, "abc", TRUE)
# [[1]]
Line 2,258 ⟶ 2,668:
#
# [[3]]
# [1] TRUE</langsyntaxhighlight>
This function is corrrect, though a little longer.
<langsyntaxhighlight lang="rsplus"> printallargs2 <- function(...)
{
args <- list(...)
Line 2,269 ⟶ 2,679:
# [1] 1 2 3 4 5
# [1] "abc"
# [1] TRUE</langsyntaxhighlight>
Use do.call to call a function with a list of arguments.
<langsyntaxhighlight lang="rsplus">arglist <- list(x=runif(10), trim=0.1, na.rm=TRUE)
do.call(mean, arglist)</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 2,279 ⟶ 2,689:
function called "vfun".
 
<syntaxhighlight lang="racket">
<lang Racket>
-> (define (vfun . xs) (for-each displayln xs))
-> (vfun)
Line 2,295 ⟶ 2,705:
13
14
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,303 ⟶ 2,713:
If a subroutine has no formal parameters but mentions the variables <code>@_</code> or <code>%_</code> in its body, it will accept arbitrary positional or keyword arguments, respectively. You can even use both in the same function.
 
<syntaxhighlight lang="raku" perl6line>sub foo {
.say for @_;
say .key, ': ', .value for %_;
Line 2,309 ⟶ 2,719:
 
foo 1, 2, command => 'buckle my shoe',
3, 4, order => 'knock at the door';</langsyntaxhighlight>
 
This prints:
Line 2,322 ⟶ 2,732:
Raku also supports slurpy arrays and hashes, which are formal parameters that consume extra positional and keyword arguments like <code>@_</code> and <code>%_</code>. You can make a parameter slurpy with the <code>*</code> twigil. This implementation of <code>&foo</code> works just like the last:
 
<syntaxhighlight lang="raku" perl6line>sub foo (*@positional, *%named) {
.say for @positional;
say .key, ': ', .value for %named;
}</langsyntaxhighlight>
 
Unlike in Perl 5, arrays and hashes aren't flattened automatically. Use the <code>|</code> operator to flatten:
 
<syntaxhighlight lang="raku" perl6line>foo |@ary, |%hsh;</langsyntaxhighlight>
 
=={{header|RapidQ}}==
RapidQ uses special keywords SUBI and FUNCTIONI for procedures and functions with variable number of parameters.
Numeric parameters are accessed from array ParamVal and string parameters from array ParamStr$.
<langsyntaxhighlight lang="rapidq">SUBI printAll (...)
FOR i = 1 TO ParamValCount
PRINT ParamVal(i)
Line 2,345 ⟶ 2,755:
printAll 4, 3, 5, 6, 4, 3
printAll 4, 3, 5
printAll "Rosetta", "Code", "Is", "Awesome!"</langsyntaxhighlight>
 
=={{header|REALbasic}}==
Line 2,351 ⟶ 2,761:
This subroutine prints it arguments. ParamArrays must be the last argument but may be preceded by any number of normal arguments.
 
<syntaxhighlight lang="vb">
<lang vb>
Sub PrintArgs(ParamArray Args() As String)
For i As Integer = 0 To Ubound(Args)
Line 2,357 ⟶ 2,767:
Next
End Sub
</syntaxhighlight>
</lang>
 
Calling the subroutine.
<syntaxhighlight lang="vb">
<lang vb>
PrintArgs("Hello", "World!", "Googbye", "World!")
</syntaxhighlight>
</lang>
 
=={{header|REBOL}}==
 
REBOL does not have variadic functions, nevertheless, it is easy to define a function taking just one argument, an ARGS block. The ARGS block contents can then be processed one by one:
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Variadic Arguments"
]
Line 2,377 ⟶ 2,787:
]
 
print-all [rebol works this way]</langsyntaxhighlight>
 
=={{header|REXX}}==
===simplistic===
<langsyntaxhighlight lang="rexx">print_all: procedure /* [↓] is the # of args passed.*/
do j=1 for arg()
say arg(j)
end /*j*/
return</langsyntaxhighlight>
 
===annotated===
<langsyntaxhighlight lang="rexx">print_all: procedure /* [↓] is the # of args passed.*/
do j=1 for arg()
say '[argument' j"]: " arg(j)
end /*j*/
return</langsyntaxhighlight>
 
===invocations===
The function can be called with any number of arguments (including no arguments and/or omitted arguments),
<br>although some REXX implementations impose a limit and the number of arguments.
<langsyntaxhighlight lang="rexx">call print_all .1,5,2,4,-3, 4.7e1, 013.000 ,, 8**2 -3, sign(-66), abs(-71.00), 8 || 9, 'seven numbers are prime, 8th is null'
 
call print_all "One ringy-dingy,",
Line 2,406 ⟶ 2,816:
"(Lily Tomlin routine)"
 
/* [↑] example showing multi-line arguments.*/</langsyntaxhighlight>
===dynamically built argument list===
<langsyntaxhighlight lang="rexx">/* REXX */
list=''
Do i=1 To 6
Line 2,420 ⟶ 2,830:
say arg(j)
end /*j*/
return</langsyntaxhighlight>
Output:
<pre>arg1
Line 2,431 ⟶ 2,841:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Variadic function
 
Line 2,455 ⟶ 2,865:
svect = left(svect, len(svect) - 1)
see "" + svect + "]"
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,461 ⟶ 2,871:
[1 2 3] 6
[1 2 3 4] 10
</pre>
 
=={{header|RPL}}==
Variable number of arguments are idiomatically passed through the stack, with the last argument specifying how many items shall be taken into account.
{{works with|HP|48G}}
≪ ""
1 ROT '''START'''
" " ROT + SWAP +
'''END''' TAIL
≫ '<span style="color:blue">MKLINE</span>' STO
 
"Mary" "has" "a" "little" "lamb" 5 <span style="color:blue">MKLINE</span>
{{out}}
<pre>
1: "Mary has a little lamb"
</pre>
 
=={{header|Ruby}}==
The * is sometimes referred to as the "splat" in Ruby.
<langsyntaxhighlight lang="ruby">def print_all(*things)
puts things
end</langsyntaxhighlight>
 
This function can be called with any number of arguments:
<langsyntaxhighlight lang="ruby">print_all(4, 3, 5, 6, 4, 3)
print_all(4, 3, 5)
print_all("Rosetta", "Code", "Is", "Awesome!")</langsyntaxhighlight>
 
You can use the same "*" syntax to apply the function to an existing list of arguments:
<langsyntaxhighlight lang="ruby">args = ["Rosetta", "Code", "Is", "Awesome!"]
print_all(*args)</langsyntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">// 20220106 Rust programming solution
 
macro_rules! print_all {
($($args:expr),*) => { $( println!("{}", $args); )* }
}
 
fn main() {
print_all!("Rosetta", "Code", "Is", "Awesome!");
}</syntaxhighlight>
Output: [https://tio.run/##PYy9CoMwAIT3PMUpDokIWocOlRZKp66@gIQ2lUB@JIm0IHn2VCt0uYPj@87NPqRU12ibtm0OzRH9umBydnRca2lGeKvmIK0hRPOHs4OblfDZikgTBq4UFgKAFrTgbvQn8Zkcq0qG8wULCrqDymQ0X2Je4UexDqxEBImEvAw0l4ay/ej/uwq99SIEvlr5zT7F1ne/5fUtvNUiy1lHYkpf Try it online!]
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def printAll(args: Any*) = args foreach println</langsyntaxhighlight>
 
Example:
Line 2,505 ⟶ 2,942:
Putting a dot before the last argument will take in any number of arguments and put them all in a list with the given name.
 
<langsyntaxhighlight lang="scheme">(define (print-all . things)
(for-each
(lambda (x) (display x) (newline))
things))</langsyntaxhighlight>
 
Note that if you define the function anonymously using <tt>lambda</tt>, and you want all the args to be collected in one list (i.e. you have no parameters before the parameter that collects everything), then you can just replace the parentheses altogether with that parameter, as if to say, let this be the argument list:
 
<langsyntaxhighlight lang="scheme">(define print-all
(lambda things
(for-each
(lambda (x) (display x) (newline))
things)))</langsyntaxhighlight>
 
This function can be called with any number of arguments:
<langsyntaxhighlight lang="scheme">(print-all 4 3 5 6 4 3)
(print-all 4 3 5)
(print-all "Rosetta" "Code" "Is" "Awesome!")</langsyntaxhighlight>
 
The <tt>apply</tt> function will apply the function to a list of arguments:
<langsyntaxhighlight lang="scheme">(define args '("Rosetta" "Code" "Is" "Awesome!"))
(apply print-all args)</langsyntaxhighlight>
 
=={{header|Sidef}}==
A parameter declared with "*", can take any number of arguments of any type.
<langsyntaxhighlight lang="ruby">func print_all(*things) {
things.each { |x| say x };
}</langsyntaxhighlight>
This function can be called with any number of arguments:
<langsyntaxhighlight lang="ruby">print_all(4, 3, 5, 6, 4, 3);
print_all(4, 3, 5);
print_all("Rosetta", "Code", "Is", "Awesome!");</langsyntaxhighlight>
Also, there is "..." which transforms an array into a list of arguments.
<langsyntaxhighlight lang="ruby">var args = ["Rosetta", "Code", "Is", "Awesome!"];
print_all(args...);</langsyntaxhighlight>
 
=={{header|Slate}}==
Line 2,544 ⟶ 2,981:
Putting an asterisk before a method's input variable header name means it will contain all non-core input variables (those are prefixed with a colon) in an Array.
 
<langsyntaxhighlight lang="slate">define: #printAll -> [| *rest | rest do: [| :arg | inform: arg printString]].
 
printAll applyTo: #(4 3 5 6 4 3).
printAll applyTo: #('Rosetta' 'Code' 'Is' 'Awesome!').</langsyntaxhighlight>
 
For method definitions and message sends, the same mechanism is employed, but the syntax for passing arguments after the message phrase is special (using commas to append arguments which fill <tt>*rest</tt>):
<langsyntaxhighlight lang="slate">_@lobby printAll [| *rest | rest do: [| :arg | inform: arg printString]].
lobby printAll, 4, 3, 5, 6, 4, 3.
lobby printAll, 'Rosetta', 'Code', 'Is', 'Awesome!'.
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
Using <tt>...</tt> after the type of argument will take in any number of arguments and put them all in one array of the given type with the given name.
<langsyntaxhighlight lang="swift">func printAll<T>(things: T...) {
// "things" is a [T]
for i in things {
print(i)
}
}</langsyntaxhighlight>
This function can be called with any number of arguments:
<langsyntaxhighlight lang="swift">printAll(4, 3, 5, 6, 4, 3)
printAll(4, 3, 5)
printAll("Rosetta", "Code", "Is", "Awesome!")</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
If the last argument is named "args", it collects all the remaining arguments
<langsyntaxhighlight lang="tcl">proc print_all {args} {puts [join $args \n]}
 
print_all 4 3 5 6 4 3
Line 2,580 ⟶ 3,017:
 
print_all $things ;# ==> incorrect: passes a single argument (a list) to print_all
print_all {*}$things ;# ==> correct: passes each element of the list to the procedure</langsyntaxhighlight>
The above code will work in all versions of Tcl except for the last line. A version-independent transcription of that (one of many possible) would be:
<langsyntaxhighlight Tcllang="tcl">eval [list print_all] [lrange $things 0 end]</langsyntaxhighlight>
 
=={{header|TIScript}}==
Line 2,588 ⟶ 3,025:
In TIScript last parameter of function may have '..' added to its name. On call that parameter will contain an array of rest of arguments passed to that function.
 
<langsyntaxhighlight lang="javascript">
function printAll(separator,argv..) {
if(argv.length)
Line 2,597 ⟶ 3,034:
printAll(" ", 4, 3, 5, 6, 4, 3);
printAll(",", 4, 3, 5);
printAll("! ","Rosetta", "Code", "Is", "Awesome");</langsyntaxhighlight>
 
=={{header|uBasic/4tH}}==
It's not easy to make a variadic function or procedure in uBasic/4tH, but it is possible with a little effort, provided the stack is used. However, sometimes it is required to reverse the order of the values by loading them into the array, from high memory to low memory. Strings may require even more effort, but the built-in hashing helps.
<syntaxhighlight lang="text">Push _Mary, _had, _a, _little, _lamb ' Push the hashes
Proc _PrintStrings (5) ' Print the string
 
Line 2,643 ⟶ 3,080:
_a Print "a"; : Return
_little Print "little"; : Return
_lamb Print "lamb"; : Return</langsyntaxhighlight>
{{out}}
<pre>Mary had a little lamb
Line 2,654 ⟶ 3,091:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">f = %gP*=
 
#show+
 
main = f <'foo',12.5,('x','y'),100></langsyntaxhighlight>
<code>f</code> is defined as a function that takes a list of any length of items of any type, and uses a built-in heuristic to decide how to print them. All functions in the language are polymorphic and variadic unless specifically restricted to the contrary.
 
Line 2,673 ⟶ 3,110:
Using a count as the indication of number of arguments to extract,
 
<langsyntaxhighlight lang="v">[myfn
[zero? not] [swap puts pred]
while
].
 
100 200 300 400 500 3 myfn</langsyntaxhighlight>
results in:
<langsyntaxhighlight lang="v">500
400
300</langsyntaxhighlight>
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|6}}
<langsyntaxhighlight lang="vb">Option Explicit
'--------------------------------------------------
Sub varargs(ParamArray a())
Line 2,725 ⟶ 3,162:
varargs v(2), v(1), v(0), 11
End Sub</langsyntaxhighlight>
{{out}}
<pre>call 1
Line 2,751 ⟶ 3,188:
12
11</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn print_all(things ...string) {
for x in things {
println(x)
}
}</syntaxhighlight>
 
=={{header|Vorpal}}==
Each method can have a variable-length parameter (VPL), indicated by empty brackets after the parameter name. The VLP (if present) will be replaced with an array containing all the extra arguments passed to the method. Effectively, extra arguments are absorbed into the array. Calling the function with fewer parameters than needed is still a runtime error. The VPL may be omitted, which will result in an empty array as the value of that parameter.
<langsyntaxhighlight lang="vorpal">self.f = method(x, y[ ], z){
x.print()
for(i = 0, i < y.size(), i = i + 1){
Line 2,766 ⟶ 3,210:
self.f(1, 2, 3, 4)
'---'.print()
self.f(1, 2)</langsyntaxhighlight>
 
=={{header|Wren}}==
Wren doesn't support variadic functions and doesn't really need to as we can just write a function which takes one (or one more) argument and pass it a list.
<langsyntaxhighlight ecmascriptlang="wren">var printArgs = Fn.new { |args| args.each { |arg| System.print(arg) } }
 
printArgs.call(["Mary", "had", "3", "little", "lambs"])</langsyntaxhighlight>
 
{{out}}
Line 2,784 ⟶ 3,228:
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">(defun print-on-separate-lines (&rest xs)
(for-each print xs))
 
Line 2,797 ⟶ 3,241:
; and then call APPLY:
 
(apply print-on-separate-lines test)</langsyntaxhighlight>
{{out}}
<pre>I
Line 2,828 ⟶ 3,272:
=={{header|XPL0}}==
Passing an array is probably a better way to accomplish this task.
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
def IntSize=4; \number of bytes in an integer
 
Line 2,839 ⟶ 3,283:
];
 
Var(4, "Mary", "had", "a", "little")</langsyntaxhighlight>
 
Output:
Line 2,851 ⟶ 3,295:
=={{header|zkl}}==
In zkl, all functions and methods are variadic (they are just passed a list).
<langsyntaxhighlight lang="zkl">fcn f{vm.arglist.apply2("println")}
f("Mary","had","a","little");</langsyntaxhighlight>
{{output}}
<pre>
Line 2,860 ⟶ 3,304:
little
</pre>
<langsyntaxhighlight lang="zkl">a:="This is a test".split(); //-->L("This","is","a","test")
f(a.xplode()); // xplode takes a list and blows it apart into call args</langsyntaxhighlight>
{{output}}
<pre>
Line 2,869 ⟶ 3,313:
test
</pre>
<langsyntaxhighlight lang="zkl">fcn g{f(vm.pasteArgs(2)}
g(a.xplode());</langsyntaxhighlight>
pasteArgs takes the passed in function args and stuffs them back into the arglist of the function call
{{output}}
2,171

edits