Variadic function: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 15: Line 15:


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(defun print-all-fn (xs)
<syntaxhighlight lang="lisp">(defun print-all-fn (xs)
(if (endp xs)
(if (endp xs)
nil
nil
Line 22: Line 22:


(defmacro print-all (&rest args)
(defmacro print-all (&rest args)
`(print-all-fn (quote ,args)))</lang>
`(print-all-fn (quote ,args)))</syntaxhighlight>


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang actionscript>public function printArgs(... args):void
<syntaxhighlight lang="actionscript">public function printArgs(... args):void
{
{
for (var i:int = 0; i < args.length; i++)
for (var i:int = 0; i < args.length; i++)
trace(args[i]);
trace(args[i]);
}</lang>
}</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
Line 35: 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.
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.


<lang Ada>with Ada.Strings.Unbounded, Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Strings.Unbounded, Ada.Text_IO;


procedure Variadic is
procedure Variadic is
Line 64: Line 64:
Print_Line((+"Mary", +"had", +"a", +"little", +"lamb.")); -- print five strings
Print_Line((+"Mary", +"had", +"a", +"little", +"lamb.")); -- print five strings
Print_Line((1 => +"Rosetta Code is cooool!")); -- print one string
Print_Line((1 => +"Rosetta Code is cooool!")); -- print one string
end;</lang>
end;</syntaxhighlight>


Output:<pre>Mary had a little lamb.
Output:<pre>Mary had a little lamb.
Line 71: Line 71:
=={{header|Aime}}==
=={{header|Aime}}==
Printing strings:
Printing strings:
<lang aime>void
<syntaxhighlight lang="aime">void
f(...)
f(...)
{
{
Line 90: Line 90:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
Printing data of assorted types:
Printing data of assorted types:
<lang aime>void
<syntaxhighlight lang="aime">void
output_date(date d)
output_date(date d)
{
{
Line 123: Line 123:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 135: 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]}}
{{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]}}
<lang algol68>main:(
<syntaxhighlight lang="algol68">main:(
MODE STRINT = UNION(STRING, INT, PROC(REF FILE)VOID, VOID);
MODE STRINT = UNION(STRING, INT, PROC(REF FILE)VOID, VOID);


Line 151: Line 151:


print strint(("Mary","had",1,"little",EMPTY,new line))
print strint(("Mary","had",1,"little",EMPTY,new line))
)</lang>
)</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 165: 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.
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.


<lang AppleScript>use framework "Foundation"
<syntaxhighlight lang="applescript">use framework "Foundation"


-- positionalArgs :: [a] -> String
-- positionalArgs :: [a] -> String
Line 259: Line 259:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<pre>"alpha
<pre>"alpha
Line 275: Line 275:
=={{header|Applesoft BASIC}}==
=={{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.
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.
<lang ApplesoftBasic>10 P$(0) = STR$(5)
<syntaxhighlight lang="applesoftbasic">10 P$(0) = STR$(5)
20 P$(1) = "MARY"
20 P$(1) = "MARY"
30 P$(2) = "HAD"
30 P$(2) = "HAD"
Line 283: Line 283:
70 GOSUB 90"VARIADIC FUNCTION
70 GOSUB 90"VARIADIC FUNCTION
80 END
80 END
90 FOR I = 1 TO VAL(P$(0)) : ? P$(I) : P$(I) = "" : NEXT I : P$(0) = "" : RETURN</lang>
90 FOR I = 1 TO VAL(P$(0)) : ? P$(I) : P$(I) = "" : NEXT I : P$(0) = "" : RETURN</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>;-------------------------------------------
<syntaxhighlight lang="rebol">;-------------------------------------------
; a quasi-variadic function
; a quasi-variadic function
;-------------------------------------------
;-------------------------------------------
Line 314: Line 314:


variable "yes"
variable "yes"
variable.with:"something" "yes!"</lang>
variable.with:"something" "yes!"</syntaxhighlight>


{{out}}
{{out}}
Line 329: Line 329:
{{works with|AutoHotkey_L}}
{{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:
Writing an asterisk after the final parameter marks the function as variadic, allowing it to receive a variable number of parameters:
<lang AutoHotkey>printAll(args*) {
<syntaxhighlight lang="autohotkey">printAll(args*) {
for k,v in args
for k,v in args
t .= v "`n"
t .= v "`n"
MsgBox, %t%
MsgBox, %t%
}</lang>
}</syntaxhighlight>
This function can be called with any number of arguments:<lang AutoHotkey>printAll(4, 3, 5, 6, 4, 3)
This function can be called with any number of arguments:<syntaxhighlight lang="autohotkey">printAll(4, 3, 5, 6, 4, 3)
printAll(4, 3, 5)
printAll(4, 3, 5)
printAll("Rosetta", "Code", "Is", "Awesome!")</lang>
printAll("Rosetta", "Code", "Is", "Awesome!")</syntaxhighlight>
An array of parameters can be passed to any function by applying the same syntax to a function-call:<lang AutoHotkey>args := ["Rosetta", "Code", "Is", "Awesome!"]
An array of parameters can be passed to any function by applying the same syntax to a function-call:<syntaxhighlight lang="autohotkey">args := ["Rosetta", "Code", "Is", "Awesome!"]
printAll(args*)</lang>
printAll(args*)</syntaxhighlight>




Line 344: 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.
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.
<lang autohotkey>string = Mary had a little lamb
<syntaxhighlight lang="autohotkey">string = Mary had a little lamb
StringSplit, arg, string, %A_Space%
StringSplit, arg, string, %A_Space%


Line 356: Line 356:
out .= arg%A_Index% "`n"
out .= arg%A_Index% "`n"
MsgBox,% out ? out:"No non-blank arguments were passed."
MsgBox,% out ? out:"No non-blank arguments were passed."
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
Line 363: Line 363:
This f() can accept 0 to 3 arguments.
This f() can accept 0 to 3 arguments.


<lang awk>function f(a, b, c){
<syntaxhighlight lang="awk">function f(a, b, c){
if (a != "") print a
if (a != "") print a
if (b != "") print b
if (b != "") print b
Line 373: Line 373:
print "[2 args]"; f(1, 2)
print "[2 args]"; f(1, 2)
print "[3 args]"; f(1, 2, 3)
print "[3 args]"; f(1, 2, 3)
}</lang>
}</syntaxhighlight>


<pre>[1 arg]
<pre>[1 arg]
Line 387: Line 387:
This f() can also accept array elements. This works because any missing array elements default to "", so f() ignores them.
This f() can also accept array elements. This works because any missing array elements default to "", so f() ignores them.


<lang awk>function f(a, b, c) {
<syntaxhighlight lang="awk">function f(a, b, c) {
if (a != "") print a
if (a != "") print a
if (b != "") print b
if (b != "") print b
Line 399: Line 399:
# Pass to f().
# Pass to f().
f(ary[1], ary[2], ary[3])
f(ary[1], ary[2], ary[3])
}</lang>
}</syntaxhighlight>


<pre>Line 1
<pre>Line 1
Line 406: 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.
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.


<lang awk>function g(len, ary, i) {
<syntaxhighlight lang="awk">function g(len, ary, i) {
for (i = 1; i <= len; i++) print ary[i];
for (i = 1; i <= len; i++) print ary[i];
}
}
Line 414: Line 414:
g(c, a) # Pass a[1] = "Line 1", a[4] = "", ...
g(c, a) # Pass a[1] = "Line 1", a[4] = "", ...


}</lang>
}</syntaxhighlight>


<pre>Line 1
<pre>Line 1
Line 425: 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.''
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.''


<lang freebasic>' Variadic functions
<syntaxhighlight lang="freebasic">' Variadic functions
OPTION BASE 1
OPTION BASE 1
SUB demo (VAR arg$ SIZE argc)
SUB demo (VAR arg$ SIZE argc)
Line 440: Line 440:
demo("abc")
demo("abc")
' Three arguments
' Three arguments
demo("123", "456", "789")</lang>
demo("123", "456", "789")</syntaxhighlight>


{{out}}
{{out}}
Line 466: 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.
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).
C calling convention has to be used (with keyword cdecl).
<lang freebasic>SUB printAll cdecl (count As Integer, ... )
<syntaxhighlight lang="freebasic">SUB printAll cdecl (count As Integer, ... )
DIM arg AS Any Ptr
DIM arg AS Any Ptr
DIM i AS Integer
DIM i AS Integer
Line 477: Line 477:
END SUB
END SUB


printAll 3, 3.1415, 1.4142, 2.71828</lang>
printAll 3, 3.1415, 1.4142, 2.71828</syntaxhighlight>
For some reason, I was not able to get a Strings version of the above to work.
For some reason, I was not able to get a Strings version of the above to work.
==={{header|FreeBASIC}}===
==={{header|FreeBASIC}}===
String version
String version
<lang freebasic>' version 15-09-2015
<syntaxhighlight lang="freebasic">' version 15-09-2015
' compile with: fbc -s console
' compile with: fbc -s console


Line 519: Line 519:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>only the last example shown
<pre>only the last example shown
Line 533: Line 533:
The existence of more parameters as well as the type of each parameter can be checked with function ITEM().
The existence of more parameters as well as the type of each parameter can be checked with function ITEM().


<lang zxbasic>100 DEF PROC printAll DATA
<syntaxhighlight lang="zxbasic">100 DEF PROC printAll DATA
110 DO UNTIL ITEM()=0
110 DO UNTIL ITEM()=0
120 IF ITEM()=1 THEN
120 IF ITEM()=1 THEN
Line 545: Line 545:


200 printAll 3.1415, 1.4142, 2.71828
200 printAll 3.1415, 1.4142, 2.71828
210 printAll "Mary", "had", "a", "little", "lamb",</lang>
210 printAll "Mary", "had", "a", "little", "lamb",</syntaxhighlight>


The code above is for Beta BASIC. There is a small difference between Beta BASIC and SAM BASIC.
The code above is for Beta BASIC. There is a small difference between Beta BASIC and SAM BASIC.
Line 553: Line 553:


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>
<syntaxhighlight lang="dos">
@echo off
@echo off


Line 567: Line 567:
:: Note: if _variadicfunc was called from cmd.exe with arguments parsed to it, it would only need to contain:
:: 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
:: @for %%i in (%*) do echo %%i
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 581: Line 581:
:c) the first element in the array specifies the number of arguments.
:c) the first element in the array specifies the number of arguments.


<lang bc>/* Version a */
<syntaxhighlight lang="bc">/* Version a */
define f(a[], l) {
define f(a[], l) {
auto i
auto i
Line 598: Line 598:
for (i = 1; i <= a[0]; i++) a[i]
for (i = 1; i <= a[0]; i++) a[i]
}</lang>
}</syntaxhighlight>


=={{header|BCPL}}==
=={{header|BCPL}}==
Line 619: Line 619:
explicitly introduces this technique.
explicitly introduces this technique.


<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


// A, B, C, etc are dummy arguments. If more are needed, more can be added.
// A, B, C, etc are dummy arguments. If more are needed, more can be added.
Line 631: Line 631:
// but you certainly needn't use them all.
// but you certainly needn't use them all.
let start() be
let start() be
foo(5, "Mary", "had", "a", "little", "lamb")</lang>
foo(5, "Mary", "had", "a", "little", "lamb")</syntaxhighlight>
{{out}}
{{out}}
<pre>Mary
<pre>Mary
Line 643: Line 643:
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.
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.


<lang bqn>Fun1 ← •Show¨
<syntaxhighlight lang="bqn">Fun1 ← •Show¨
Fun2 ← {•Show¨𝕩}
Fun2 ← {•Show¨𝕩}
Fun3 ← { 1=≠𝕩 ? •Show 𝕩; "too many arguments " ! 𝕩}</lang>
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.
Both <tt>Fun1</tt> and <tt>Fun2</tt> display all the values (arguments) of the lists given to them.
Line 653: Line 653:
=={{header|C}}==
=={{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.
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.
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdarg.h>
#include <stdarg.h>


Line 665: Line 665:
}
}


varstrings(5, "Mary", "had", "a", "little", "lamb");</lang>
varstrings(5, "Mary", "had", "a", "little", "lamb");</syntaxhighlight>


In C, there is no way to call a variadic function on a list of arguments constructed at runtime.
In C, there is no way to call a variadic function on a list of arguments constructed at runtime.
Line 677: Line 677:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


class Program {
class Program {
Line 689: Line 689:
}
}
}
}
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 707: Line 707:
{{works with|g++|4.3.0}} using option -std=c++0x
{{works with|g++|4.3.0}} using option -std=c++0x


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


template<typename T>
template<typename T>
Line 727: Line 727:
std::string s = "Hello world";
std::string s = "Hello world";
print("i = ", i, " and s = \"", s, "\"\n");
print("i = ", i, " and s = \"", s, "\"\n");
}</lang>
}</syntaxhighlight>
As the example shows, variadic templates allow any type to be passed.
As the example shows, variadic templates allow any type to be passed.


=={{header|Clojure}}==
=={{header|Clojure}}==


<lang lisp>(defn foo [& args]
<syntaxhighlight lang="lisp">(defn foo [& args]
(doseq [a args]
(doseq [a args]
(println a)))
(println a)))


(foo :bar :baz :quux)
(foo :bar :baz :quux)
(apply foo [:bar :baz :quux])</lang>
(apply foo [:bar :baz :quux])</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|Micro Focus COBOL V3.2}}
{{works with|Micro Focus COBOL V3.2}}
<lang>
<syntaxhighlight lang="text">
program-id. dsp-str is external.
program-id. dsp-str is external.
data division.
data division.
Line 800: Line 800:
.
.
end program dsp-str.
end program dsp-str.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 814: Line 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.
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.


<lang lisp>(defun example (&rest args)
<syntaxhighlight lang="lisp">(defun example (&rest args)
(dolist (arg args)
(dolist (arg args)
(print arg)))
(print arg)))
Line 821: Line 821:


(let ((args '("Mary" "had" "a" "little" "lamb")))
(let ((args '("Mary" "had" "a" "little" "lamb")))
(apply #'example args))</lang>
(apply #'example args))</syntaxhighlight>


=={{header|Coq}}==
=={{header|Coq}}==
To define a variadic function, we build a variadic type:
To define a variadic function, we build a variadic type:


<lang coq>
<syntaxhighlight lang="coq">
Fixpoint Arity (A B: Set) (n: nat): Set := match n with
Fixpoint Arity (A B: Set) (n: nat): Set := match n with
|O => B
|O => B
|S n' => A -> (Arity A B n')
|S n' => A -> (Arity A B n')
end.
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> .
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 839: Line 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:
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:
<lang coq>
<syntaxhighlight lang="coq">
Definition nat_twobools (n: nat) := Arity nat (Arity bool nat (2*n)) n.
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 \>
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 850: Line 850:
Finally, for the function to work, we need an accumulator of some sort
Finally, for the function to work, we need an accumulator of some sort


<lang coq>
<syntaxhighlight lang="coq">
Require Import List.
Require Import List.
Fixpoint build_list_aux {A: Set} (acc: list A) (n : nat): Arity A (list A) n := match n with
Fixpoint build_list_aux {A: Set} (acc: list A) (n : nat): Arity A (list A) n := match n with
Line 856: Line 856:
|S n' => fun (val: A) => build_list_aux (acc ++ (val :: nil)) n'
|S n' => fun (val: A) => build_list_aux (acc ++ (val :: nil)) n'
end.
end.
</syntaxhighlight>
</lang>


Our function is then just an application of this one:
Our function is then just an application of this one:
<lang coq>
<syntaxhighlight lang="coq">
Definition build_list {A: Set} := build_list_aux (@nil A).
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
To call it we give it the number of argument and then the parameters we want in the list
<lang coq>
<syntaxhighlight lang="coq">
Check build_list 5 1 2 5 90 42.
Check build_list 5 1 2 5 90 42.
</syntaxhighlight>
</lang>
Which gives the result [1; 2; 5; 90; 42]
Which gives the result [1; 2; 5; 90; 42]


Line 874: Line 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:
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:


<lang coq>
<syntaxhighlight lang="coq">
Lemma transparent_plus_zero: forall n, n + O = n.
Lemma transparent_plus_zero: forall n, n + O = n.
intros n; induction n.
intros n; induction n.
Line 886: Line 886:
- simpl; f_equal; rewrite IHn; reflexivity.
- simpl; f_equal; rewrite IHn; reflexivity.
Defined.
Defined.
</syntaxhighlight>
</lang>


Now on to the function. <br \>
Now on to the function. <br \>
Line 893: Line 893:
Instead of defining a function directly, we will construct it as a proof that will be easier for us to write:
Instead of defining a function directly, we will construct it as a proof that will be easier for us to write:


<lang coq>
<syntaxhighlight lang="coq">
Require Import Vector.
Require Import Vector.


Line 901: Line 901:
- intros val. rewrite transparent_plus_S. apply IHn. (*Here we use the induction hypothesis. We just have to build the new accumulator*)
- 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*)
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:
As before, we can now build the full function with a null accumulator:
<lang coq>
<syntaxhighlight lang="coq">
Definition build_vector {A: Set} (n: nat) := build_vector_aux n O (@nil A).
Definition build_vector {A: Set} (n: nat) := build_vector_aux n O (@nil A).
</syntaxhighlight>
</lang>


When we call it:
When we call it:
<lang coq>
<syntaxhighlight lang="coq">
Require Import String.
Require Import String.
Eval compute in build_vector 4 "Hello" "how" "are" "you".
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
Which gives the vector of members "Hello", "how", "are" and "you" of size 4


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.algorithm;


void printAll(TyArgs...)(TyArgs args) {
void printAll(TyArgs...)(TyArgs args) {
Line 938: Line 938:
showSum1(1, 3, 50);
showSum1(1, 3, 50);
showSum2(1, 3, 50, 10);
showSum2(1, 3, 50, 10);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>4
<pre>4
Line 961: Line 961:
=={{header|Dyalect}}==
=={{header|Dyalect}}==


<lang Dyalect>func printAll(args...) {
<syntaxhighlight lang="dyalect">func printAll(args...) {
for i in args {
for i in args {
print(i)
print(i)
Line 967: Line 967:
}
}


printAll("test", "rosetta code", 123, 5.6)</lang>
printAll("test", "rosetta code", 123, 5.6)</syntaxhighlight>


{{out}}
{{out}}
Line 980: Line 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>).
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>).


<lang dejavu>show-all(:
<syntaxhighlight lang="dejavu">show-all(:
while /= ) dup:
while /= ) dup:
!.
!.
drop
drop


show-all( :foo "Hello" 42 [ true ] )</lang>
show-all( :foo "Hello" 42 [ true ] )</syntaxhighlight>
{{out}}
{{out}}
<pre>:foo
<pre>:foo
Line 998: Line 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:
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:


<lang e>def example {
<syntaxhighlight lang="e">def example {
match [`run`, args] {
match [`run`, args] {
for x in args {
for x in args {
Line 1,008: Line 1,008:
example("Mary", "had", "a", "little", "lamb")
example("Mary", "had", "a", "little", "lamb")


E.call(example, "run", ["Mary", "had", "a", "little", "lamb"])</lang>
E.call(example, "run", ["Mary", "had", "a", "little", "lamb"])</syntaxhighlight>




For comparison, a plain method doing the same thing for exactly two arguments would be like this:
For comparison, a plain method doing the same thing for exactly two arguments would be like this:


<lang e>def non_example {
<syntaxhighlight lang="e">def non_example {
to run(x, y) {
to run(x, y) {
println(x)
println(x)
println(y)
println(y)
}
}
}</lang>
}</syntaxhighlight>


or, written using the function syntax,
or, written using the function syntax,


<lang e>def non_example(x, y) {
<syntaxhighlight lang="e">def non_example(x, y) {
println(x)
println(x)
println(y)
println(y)
}</lang>
}</syntaxhighlight>


=={{header|Egel}}==
=={{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.
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" ]
[ X Y -> "two" | X -> "one" | -> "zero" ]
</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.1 :
ELENA 4.1 :
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;
Line 1,053: Line 1,053:
{
{
console.printAll("test", "rosetta code", 123, 5.6r)
console.printAll("test", "rosetta code", 123, 5.6r)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,065: Line 1,065:
Elixir doesn't have the feature of the variable number of arguments.
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 [].
However, it is possible to process as the list if putting in an argument in [].
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def print_each( arguments ) do
def print_each( arguments ) do
Enum.each(arguments, fn x -> IO.inspect x end)
Enum.each(arguments, fn x -> IO.inspect x end)
Line 1,072: Line 1,072:


RC.print_each([1,2,3])
RC.print_each([1,2,3])
RC.print_each(["Mary", "had", "a", "little", "lamb"])</lang>
RC.print_each(["Mary", "had", "a", "little", "lamb"])</syntaxhighlight>


{{out}}
{{out}}
Line 1,090: Line 1,090:
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.
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.


<lang Lisp>(defun my-print-args (&rest arg-list)
<syntaxhighlight lang="lisp">(defun my-print-args (&rest arg-list)
(message "there are %d argument(s)" (length arg-list))
(message "there are %d argument(s)" (length arg-list))
(dolist (arg arg-list)
(dolist (arg arg-list)
(message "arg is %S" arg)))
(message "arg is %S" arg)))


(my-print-args 1 2 3)</lang>
(my-print-args 1 2 3)</syntaxhighlight>


A function can be called with a list of arguments (and optionally fixed arguments too) with <code>apply</code>, similar to most Lisp variants.
A function can be called with a list of arguments (and optionally fixed arguments too) with <code>apply</code>, similar to most Lisp variants.


<lang Lisp>(let ((arg-list '("some thing %d %d %d" 1 2 3)))
<syntaxhighlight lang="lisp">(let ((arg-list '("some thing %d %d %d" 1 2 3)))
(apply 'message arg-list))</lang>
(apply 'message arg-list))</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Variable amount of anything (like arguments): use a list.
Variable amount of anything (like arguments): use a list.
<syntaxhighlight lang="erlang">
<lang Erlang>
print_each( Arguments ) -> [io:fwrite( "~p~n", [X]) || X <- Arguments].
print_each( Arguments ) -> [io:fwrite( "~p~n", [X]) || X <- Arguments].
</syntaxhighlight>
</lang>


=={{header|Euler Math Toolbox}}==
=={{header|Euler Math Toolbox}}==


<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function allargs () ...
>function allargs () ...
$ loop 1 to argn();
$ loop 1 to argn();
Line 1,126: Line 1,126:
16
16
64
64
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>procedure print_args(sequence args)
<syntaxhighlight lang="euphoria">procedure print_args(sequence args)
for i = 1 to length(args) do
for i = 1 to length(args) do
puts(1,args[i])
puts(1,args[i])
Line 1,136: Line 1,136:
end procedure
end procedure


print_args({"Mary", "had", "a", "little", "lamb"})</lang>
print_args({"Mary", "had", "a", "little", "lamb"})</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
Variadic functions can be created by making a word which accepts a number specifying how many data stack items to operate on.
Variadic functions can be created by making a word which accepts a number specifying how many data stack items to operate on.
<lang factor>MACRO: variadic-print ( n -- quot ) [ print ] n*quot ;</lang>
<syntaxhighlight lang="factor">MACRO: variadic-print ( n -- quot ) [ print ] n*quot ;</syntaxhighlight>
An interactive demonstration in the listener:
An interactive demonstration in the listener:
<lang factor>IN: scratchpad "apple" "banana" "cucumber"
<syntaxhighlight lang="factor">IN: scratchpad "apple" "banana" "cucumber"


--- Data stack:
--- Data stack:
Line 1,154: Line 1,154:


--- Data stack:
--- Data stack:
"apple"</lang>
"apple"</syntaxhighlight>


=={{header|Forth}}==
=={{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.
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.


<lang forth>: sum ( x_1 ... x_n n -- sum ) 1 ?do + loop ;
<syntaxhighlight lang="forth">: sum ( x_1 ... x_n n -- sum ) 1 ?do + loop ;
4 3 2 1 4 sum . \ 10</lang>
4 3 2 1 4 sum . \ 10</syntaxhighlight>


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


<lang forth>: .stack ( -- ) depth 0 ?do i pick . loop ;</lang>
<syntaxhighlight lang="forth">: .stack ( -- ) depth 0 ?do i pick . loop ;</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 1,172: Line 1,172:
The following code shows how an optional vector argument can be used to pass a variable number of argument to a subroutine.
The following code shows how an optional vector argument can be used to pass a variable number of argument to a subroutine.


<lang fortran>program varargs
<syntaxhighlight lang="fortran">program varargs


integer, dimension(:), allocatable :: va
integer, dimension(:), allocatable :: va
Line 1,204: Line 1,204:
end subroutine v_func
end subroutine v_func


end program varargs</lang>
end program varargs</syntaxhighlight>


=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
Note, strictly speaking the routine <tt>writeLines</tt> has exactly ''one'' parameter.
Note, strictly speaking the routine <tt>writeLines</tt> has exactly ''one'' parameter.
<lang pascal>program variadicRoutinesDemo(input, output, stdErr);
<syntaxhighlight lang="pascal">program variadicRoutinesDemo(input, output, stdErr);
{$mode objFPC}
{$mode objFPC}


Line 1,246: Line 1,246:
begin
begin
writeLines([42, 'is', true, #33]);
writeLines([42, 'is', true, #33]);
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<lang text>42
<syntaxhighlight lang="text">42
is
is
TRUE
TRUE
!</lang>
!</syntaxhighlight>


=={{header|Fōrmulæ}}==
=={{header|Fōrmulæ}}==
Line 1,262: Line 1,262:


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang futurebasic>void local fn Function1( count as long, ... )
<syntaxhighlight lang="futurebasic">void local fn Function1( count as long, ... )
va_list ap
va_list ap
long value
long value
Line 1,298: Line 1,298:
fn Function2( @"One", @"Two", @"Three", @"O'Leary", NULL )
fn Function2( @"One", @"Two", @"Three", @"O'Leary", NULL )


HandleEvents</lang>
HandleEvents</syntaxhighlight>
{{Out}}
{{Out}}
<pre>987
<pre>987
Line 1,312: Line 1,312:
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)]
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)]


<lang go>func printAll(things ... string) {
<syntaxhighlight lang="go">func printAll(things ... string) {
// it's as if you declared "things" as a []string, containing all the arguments
// it's as if you declared "things" as a []string, containing all the arguments
for _, x := range things {
for _, x := range things {
fmt.Println(x)
fmt.Println(x)
}
}
}</lang>
}</syntaxhighlight>


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:
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:
<lang go>args := []string{"foo", "bar"}
<syntaxhighlight lang="go">args := []string{"foo", "bar"}
printAll(args...)</lang>
printAll(args...)</syntaxhighlight>


=={{header|Golo}}==
=={{header|Golo}}==
<lang golo>#!/usr/bin/env golosh
<syntaxhighlight lang="golo">#!/usr/bin/env golosh
----
----
This module demonstrates variadic functions.
This module demonstrates variadic functions.
Line 1,347: Line 1,347:
# to call a variadic function with an array we use the unary function
# to call a variadic function with an array we use the unary function
unary(^varargsFunc)(args)
unary(^varargsFunc)(args)
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def printAll( Object[] args) { args.each{ arg -> println arg } }
<syntaxhighlight lang="groovy">def printAll( Object[] args) { args.each{ arg -> println arg } }


printAll(1, 2, "three", ["3", "4"])</lang>
printAll(1, 2, "three", ["3", "4"])</syntaxhighlight>


Sample output:
Sample output:
Line 1,362: Line 1,362:
=={{header|Haskell}}==
=={{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.
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.
<lang haskell>class PrintAllType t where
<syntaxhighlight lang="haskell">class PrintAllType t where
process :: [String] -> t
process :: [String] -> t


Line 1,378: Line 1,378:
main = do printAll 5 "Mary" "had" "a" "little" "lamb"
main = do printAll 5 "Mary" "had" "a" "little" "lamb"
printAll 4 3 5
printAll 4 3 5
printAll "Rosetta" "Code" "Is" "Awesome!"</lang>
printAll "Rosetta" "Code" "Is" "Awesome!"</syntaxhighlight>
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.
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 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 :
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 :
<lang haskell>{-# LANGUAGE GADTs #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE GADTs #-}
...
...


Line 1,389: Line 1,389:
process args = do mapM_ putStrLn args
process args = do mapM_ putStrLn args


...</lang>
...</syntaxhighlight>


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.
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,398: Line 1,398:
varargs.icn
varargs.icn


<lang icon>procedure main ()
<syntaxhighlight lang="icon">procedure main ()
varargs("some", "extra", "args")
varargs("some", "extra", "args")
write()
write()
Line 1,406: Line 1,406:
procedure varargs(args[])
procedure varargs(args[])
every write(!args)
every write(!args)
end</lang>
end</syntaxhighlight>


Using it
Using it
Line 1,420: Line 1,420:


=={{header|Io}}==
=={{header|Io}}==
<lang io>printAll := method(call message arguments foreach(println))</lang>
<syntaxhighlight lang="io">printAll := method(call message arguments foreach(println))</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 1,428: Line 1,428:
For example:
For example:


<lang J> A=:2
<syntaxhighlight lang="j"> A=:2
B=:3
B=:3
C=:5
C=:5
sum=:+/
sum=:+/
sum 1,A,B,4,C
sum 1,A,B,4,C
15</lang>
15</syntaxhighlight>


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


<lang J> commaAnd=: [: ; (<' and ') _2} ::] 1 }.&, (<', ') ,. ":each
<syntaxhighlight lang="j"> commaAnd=: [: ; (<' and ') _2} ::] 1 }.&, (<', ') ,. ":each
commaAnd 'dog';A;B;'cat';C
commaAnd 'dog';A;B;'cat';C
dog, 2, 3, cat and 5</lang>
dog, 2, 3, cat and 5</syntaxhighlight>


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


<lang J> echo&>'dog';A;B;'cat';C
<syntaxhighlight lang="j"> echo&>'dog';A;B;'cat';C
dog
dog
2
2
3
3
cat
cat
5</lang>
5</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{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.
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.
<lang java5>public static void printAll(Object... things){
<syntaxhighlight lang="java5">public static void printAll(Object... things){
// "things" is an Object[]
// "things" is an Object[]
for(Object i:things){
for(Object i:things){
System.out.println(i);
System.out.println(i);
}
}
}</lang>
}</syntaxhighlight>
This function can be called with any number of arguments:
This function can be called with any number of arguments:
<lang java5>printAll(4, 3, 5, 6, 4, 3);
<syntaxhighlight lang="java5">printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!");</lang>
printAll("Rosetta", "Code", "Is", "Awesome!");</syntaxhighlight>


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>):
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>):
<lang java5>Object[] args = {"Rosetta", "Code", "Is", "Awesome!"};
<syntaxhighlight lang="java5">Object[] args = {"Rosetta", "Code", "Is", "Awesome!"};
printAll(args);</lang>
printAll(args);</syntaxhighlight>


But not with both (in this case the array is considered as just one of two arguments, and not expanded):
But not with both (in this case the array is considered as just one of two arguments, and not expanded):
<lang java5>Object[] args = {"Rosetta", "Code", "Is", "Awesome,"};
<syntaxhighlight lang="java5">Object[] args = {"Rosetta", "Code", "Is", "Awesome,"};
printAll(args, "Dude!");//does not print "Rosetta Code Is Awesome, Dude!"
printAll(args, "Dude!");//does not print "Rosetta Code Is Awesome, Dude!"
//instead prints the type and hashcode for args followed by "Dude!"</lang>
//instead prints the type and hashcode for args followed by "Dude!"</syntaxhighlight>


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.
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.
<lang java5>printAll((Object)args);</lang>
<syntaxhighlight lang="java5">printAll((Object)args);</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===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.
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.
<lang javascript>function printAll() {
<syntaxhighlight lang="javascript">function printAll() {
for (var i=0; i<arguments.length; i++)
for (var i=0; i<arguments.length; i++)
print(arguments[i])
print(arguments[i])
Line 1,485: Line 1,485:
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!");</lang>
printAll("Rosetta", "Code", "Is", "Awesome!");</syntaxhighlight>
The <code><var>function</var>.arguments</code> property is equivalent to the <code>arguments</code> variable above, but is deprecated.
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:
You can use the <tt>apply</tt> method of a function to apply it to a list of arguments:
<lang javascript>args = ["Rosetta", "Code", "Is", "Awesome!"]
<syntaxhighlight lang="javascript">args = ["Rosetta", "Code", "Is", "Awesome!"]
printAll.apply(null, args)</lang>
printAll.apply(null, args)</syntaxhighlight>


===ECMAScript 2015 (ES6) variants===
===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:
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:
<lang javascript>let
<syntaxhighlight lang="javascript">let
fix = // Variant of the applicative order Y combinator
fix = // Variant of the applicative order Y combinator
f => (f => f(f))(g => f((...a) => g(g)(...a))),
f => (f => f(f))(g => f((...a) => g(g)(...a))),
Line 1,523: Line 1,523:
// 13
// 13
// 14
// 14
</syntaxhighlight>
</lang>


Or, less ambitiously:
Or, less ambitiously:


<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 1,538: Line 1,538:


return printAll(1, 2, 3, 2 + 2, "five", 6);
return printAll(1, 2, 3, 2 + 2, "five", 6);
})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,554: Line 1,554:


The first task requirement can in effect be accomplished using a 0-arity function defined as follows:
The first task requirement can in effect be accomplished using a 0-arity function defined as follows:
<lang jq>def demo: .[];</lang>
<syntaxhighlight lang="jq">def demo: .[];</syntaxhighlight>


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:
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:
<lang jq>args | demo</lang>
<syntaxhighlight lang="jq">args | demo</syntaxhighlight>
For example:
For example:
<lang jq>["cheese"] + [3.14] + [[range(0;3)]] | demo</lang>
<syntaxhighlight lang="jq">["cheese"] + [3.14] + [[range(0;3)]] | demo</syntaxhighlight>
produces:
produces:
<lang sh>"cheese"
<syntaxhighlight lang="sh">"cheese"
3.14
3.14
[0,1,2]</lang>
[0,1,2]</syntaxhighlight>


'''Variadic Function Names''':
'''Variadic Function Names''':
Line 1,570: Line 1,570:


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.
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:
# arity-0:
def f: "I have no arguments";
def f: "I have no arguments";
Line 1,583: Line 1,583:


# Example:
# Example:
f, f(1), f(2;3), f(4;5;6)</lang>
f, f(1), f(2;3), f(4;5;6)</syntaxhighlight>
produces:
produces:
<lang sh>1
<syntaxhighlight lang="sh">1
2
2
3
3
4
4
5
5
6</lang>
6</syntaxhighlight>


=={{header|Julia}}==
=={{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):
Putting <code>...</code> after the last argument in a function definition makes it variadic (any number of arguments are passed as a tuple):
<lang julia>
<syntaxhighlight lang="julia">
julia> print_each(X...) = for x in X; println(x); end
julia> print_each(X...) = for x in X; println(x); end


Line 1,601: Line 1,601:
hello
hello
23.4
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:
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:
<lang julia>
<syntaxhighlight lang="julia">
julia> args = [ "first", (1,2,17), "last" ]
julia> args = [ "first", (1,2,17), "last" ]
3-element Array{Any,1}:
3-element Array{Any,1}:
Line 1,614: Line 1,614:
(1,2,17)
(1,2,17)
last
last
</syntaxhighlight>
</lang>


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang Klingphix>:varfunc
<syntaxhighlight lang="klingphix">:varfunc
1 tolist flatten
1 tolist flatten
len [
len [
Line 1,628: Line 1,628:
stklen [split varfunc nl] if
stklen [split varfunc nl] if


nl "End " input</lang>
nl "End " input</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1
<syntaxhighlight lang="scala">// version 1.1


fun variadic(vararg va: String) {
fun variadic(vararg va: String) {
Line 1,647: Line 1,647:
println()
println()
variadic(*va)
variadic(*va)
}</lang>
}</syntaxhighlight>
Sample input/output:
Sample input/output:
{{out}}
{{out}}
Line 1,668: Line 1,668:


=={{header|Ksh}}==
=={{header|Ksh}}==
<lang ksh>
<syntaxhighlight lang="ksh">
#!/bin/ksh
#!/bin/ksh


Line 1,692: Line 1,692:
_variadic Mary had a little lamb
_variadic Mary had a little lamb
echo
echo
_variadic ${arr[@]}</lang>
_variadic ${arr[@]}</syntaxhighlight>
{{out}}<pre>
{{out}}<pre>
Mary
Mary
Line 1,708: Line 1,708:
=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
Lambdas are de facto variadic in lambdatalk
Lambdas are de facto variadic in lambdatalk
<lang scheme>
<syntaxhighlight lang="scheme">
{def foo
{def foo
{lambda {:s}
{lambda {:s}
Line 1,733: Line 1,733:
10
10


</syntaxhighlight>
</lang>


=={{header|Lasso}}==
=={{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".
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".
<lang lasso>define printArgs(...items) => stdoutnl(#items)
<syntaxhighlight lang="lasso">define printArgs(...items) => stdoutnl(#items)
define printEachArg(...) => with i in #rest do stdoutnl(#i)
define printEachArg(...) => with i in #rest do stdoutnl(#i)


printArgs('a', 2, (:3))
printArgs('a', 2, (:3))
printEachArg('a', 2, (:3))</lang>
printEachArg('a', 2, (:3))</syntaxhighlight>
To expand an existing list, pass it to the method using invocation syntax.
To expand an existing list, pass it to the method using invocation syntax.
<lang lasso>local(args = (:"Rosetta", "Code", "Is", "Awesome!"))
<syntaxhighlight lang="lasso">local(args = (:"Rosetta", "Code", "Is", "Awesome!"))
printEachArg(:#args)</lang>
printEachArg(:#args)</syntaxhighlight>
Output:
Output:
<lang lasso>staticarray(a, 2, staticarray(3))
<syntaxhighlight lang="lasso">staticarray(a, 2, staticarray(3))
a
a
2
2
Line 1,753: Line 1,753:
Code
Code
Is
Is
Awesome!</lang>
Awesome!</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
Line 1,762: Line 1,762:
# an optional "rest" input (a list containing a colon prefixed word, set to the list of remaining arguments)
# 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)
# ...with an optional default arity (a number)
<lang logo>to varargs [:args]
<syntaxhighlight lang="logo">to varargs [:args]
foreach :args [print ?]
foreach :args [print ?]
end
end


(varargs "Mary "had "a "little "lamb)
(varargs "Mary "had "a "little "lamb)
apply "varargs [Mary had a little lamb]</lang>
apply "varargs [Mary had a little lamb]</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Line 1,773: Line 1,773:
The generic syntax for defining a variadic function is appending an ellipsis to the list of arguments:
The generic syntax for defining a variadic function is appending an ellipsis to the list of arguments:


<lang lua>function varar(...)
<syntaxhighlight lang="lua">function varar(...)
for i, v in ipairs{...} do print(v) end
for i, v in ipairs{...} do print(v) end
end</lang>
end</syntaxhighlight>


It is then used like so:
It is then used like so:


<lang lua>varar(1, "bla", 5, "end");</lang>
<syntaxhighlight lang="lua">varar(1, "bla", 5, "end");</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 1,788: Line 1,788:
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:
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:


<lang lua>local runtime_array = {1, "bla", 5, "end"};
<syntaxhighlight lang="lua">local runtime_array = {1, "bla", 5, "end"};


varar(unpack(runtime_array));</lang>
varar(unpack(runtime_array));</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 1,804: Line 1,804:
Module's have stack too, but calling a module from module pass the same stack. This hold if we call function using Call statement.
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 {
Module CheckIt {
\\ Works for numbers and strings (letters in M2000)
\\ Works for numbers and strings (letters in M2000)
Line 1,843: Line 1,843:
}
}
Checkit2
Checkit2
</syntaxhighlight>
</lang>


=={{header|M4}}==
=={{header|M4}}==
<lang M4>define(`showN',
<syntaxhighlight lang="m4">define(`showN',
`ifelse($1,0,`',`$2
`ifelse($1,0,`',`$2
$0(decr($1),shift(shift($@)))')')dnl
$0(decr($1),shift(shift($@)))')')dnl
Line 1,855: Line 1,855:
define(`x',`1,2')
define(`x',`1,2')
define(`y',`,3,4,5')
define(`y',`,3,4,5')
showargs(x`'y)</lang>
showargs(x`'y)</syntaxhighlight>


Output (with tracing):
Output (with tracing):
Line 1,876: Line 1,876:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Function that takes 0 to infinite arguments and prints the arguments:
Function that takes 0 to infinite arguments and prints the arguments:
<lang Mathematica>ShowMultiArg[x___] := Do[Print[i], {i, {x}}]</lang>
<syntaxhighlight lang="mathematica">ShowMultiArg[x___] := Do[Print[i], {i, {x}}]</syntaxhighlight>
Example:
Example:
<lang Mathematica>ShowMultiArg[]
<syntaxhighlight lang="mathematica">ShowMultiArg[]
ShowMultiArg[a, b, c]
ShowMultiArg[a, b, c]
ShowMultiArg[5, 3, 1]</lang>
ShowMultiArg[5, 3, 1]</syntaxhighlight>
gives back:
gives back:
<lang Mathematica>[nothing]
<syntaxhighlight lang="mathematica">[nothing]


a
a
Line 1,890: Line 1,890:
5
5
3
3
1</lang>
1</syntaxhighlight>
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.
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,896: Line 1,896:
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.
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.


<lang MATLAB>function variadicFunction(varargin)
<syntaxhighlight lang="matlab">function variadicFunction(varargin)


for i = (1:numel(varargin))
for i = (1:numel(varargin))
Line 1,902: Line 1,902:
end
end
end</lang>
end</syntaxhighlight>


Sample Usage:
Sample Usage:
<lang MATLAB>>> variadicFunction(1,2,3,4,'cat')
<syntaxhighlight lang="matlab">>> variadicFunction(1,2,3,4,'cat')
1
1


Line 1,914: Line 1,914:
4
4


cat</lang>
cat</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>show([L]) := block([n], n: length(L), for i from 1 thru n do disp(L[i]))$
<syntaxhighlight lang="maxima">show([L]) := block([n], n: length(L), for i from 1 thru n do disp(L[i]))$


show(1, 2, 3, 4);
show(1, 2, 3, 4);
Line 1,926: Line 1,926:
disp(1, 2, 3, 4);
disp(1, 2, 3, 4);


apply(disp, [1, 2, 3, 4]);</lang>
apply(disp, [1, 2, 3, 4]);</syntaxhighlight>


=={{header|Metafont}}==
=={{header|Metafont}}==
Line 1,932: Line 1,932:
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)
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)


<lang metafont>def print_arg(text t) =
<syntaxhighlight lang="metafont">def print_arg(text t) =
for x = t:
for x = t:
if unknown x: message "unknown value"
if unknown x: message "unknown value"
Line 1,945: Line 1,945:


print_arg("hello", x, 12, fullcircle, currentpicture, down, identity, false, pencircle);
print_arg("hello", x, 12, fullcircle, currentpicture, down, identity, false, pencircle);
end</lang>
end</syntaxhighlight>


=={{header|Modula-3}}==
=={{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.
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.
<lang modula3>MODULE Varargs EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Varargs EXPORTS Main;


IMPORT IO;
IMPORT IO;
Line 1,964: Line 1,964:
BEGIN
BEGIN
Variable(strings);
Variable(strings);
END Varargs.</lang>
END Varargs.</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,974: Line 1,974:
</pre>
</pre>
Things get more complicated if you want to mix types:
Things get more complicated if you want to mix types:
<lang modula3>MODULE Varargs EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Varargs EXPORTS Main;


IMPORT IO, Fmt;
IMPORT IO, Fmt;
Line 1,999: Line 1,999:
strings^ := "Rosetta"; ints^ := 1; reals^ := 3.1415;
strings^ := "Rosetta"; ints^ := 1; reals^ := 3.1415;
Variable(refarr);
Variable(refarr);
END Varargs.</lang>
END Varargs.</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,010: Line 2,010:
{{trans|C#}}
{{trans|C#}}
Like C#, Nemerle uses the <tt>params</tt> keyword to specify that arguments are collected into an array.
Like C#, Nemerle uses the <tt>params</tt> keyword to specify that arguments are collected into an array.
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;


Line 2,024: Line 2,024:
PrintAll("test", "rosetta code", 123, 5.6, DateTime.Now);
PrintAll("test", "rosetta code", 123, 5.6, DateTime.Now);
}
}
}</lang>
}</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>proc print(xs: varargs[string, `$`]) =
<syntaxhighlight lang="nim">proc print(xs: varargs[string, `$`]) =
for x in xs:
for x in xs:
echo x</lang>
echo x</syntaxhighlight>
The function can be called with any number of arguments and the argument list can be constructed at runtime:
The function can be called with any number of arguments and the argument list can be constructed at runtime:
<lang nim>print(12, "Rosetta", "Code", 15.54321)
<syntaxhighlight lang="nim">print(12, "Rosetta", "Code", 15.54321)


print 12, "Rosetta", "Code", 15.54321, "is", "awesome!"
print 12, "Rosetta", "Code", 15.54321, "is", "awesome!"


let args = @["12", "Rosetta", "Code", "15.54321"]
let args = @["12", "Rosetta", "Code", "15.54321"]
print(args)</lang>
print(args)</syntaxhighlight>


=={{header|Objective-C}}==
=={{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>.
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>.


<lang objc>#include <stdarg.h>
<syntaxhighlight 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
void logObjects(id firstObject, ...) // <-- there is always at least one arg, "nil", so this is valid, even for "empty" list
Line 2,055: Line 2,055:
// This function can be called with any number or type of objects, as long as you terminate it with "nil":
// 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(@"Rosetta", @"Code", @"Is", @"Awesome!", nil);
logObjects(@4, @3, @"foo", nil);</lang>
logObjects(@4, @3, @"foo", nil);</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
OCaml's strong type system makes writing variadic functions complex, as there is no <code>'a... -> 'b</code> type.
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 :
In general, writing a function that takes a list as argument is the best practice :
<lang ocaml>let rec print = function
<syntaxhighlight lang="ocaml">let rec print = function
| [] -> ()
| [] -> ()
| x :: xs -> print_endline x; print xs
| x :: xs -> print_endline x; print xs
Line 2,069: Line 2,069:
let () =
let () =
print [];
print [];
print ["hello"; "world!"]</lang>
print ["hello"; "world!"]</syntaxhighlight>


If you really need a true variadic function, there are a few ways to make it work.
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) :
The first is to specify the function's type with its first argument using a generalized algebraic data type (GADT) :


<lang ocaml>type 'a variadic =
<syntaxhighlight lang="ocaml">type 'a variadic =
| Z : unit variadic
| Z : unit variadic
| S : 'a variadic -> (string -> 'a) variadic
| S : 'a variadic -> (string -> 'a) variadic
Line 2,085: Line 2,085:
print Z; (* no arguments *)
print Z; (* no arguments *)
print (S Z) "hello"; (* one argument *)
print (S Z) "hello"; (* one argument *)
print (S (S (S Z))) "how" "are" "you" (* three arguments *)</lang>
print (S (S (S Z))) "how" "are" "you" (* three arguments *)</syntaxhighlight>


You can even specify different types with more GADT constructors:
You can even specify different types with more GADT constructors:
<lang ocaml>type 'a variadic =
<syntaxhighlight lang="ocaml">type 'a variadic =
| Z : unit variadic
| Z : unit variadic
| U : 'a variadic -> (unit -> 'a) variadic
| U : 'a variadic -> (unit -> 'a) variadic
Line 2,109: Line 2,109:
let () =
let () =
print (S (I (S Z))) "I am " 5 "Years old";
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]</lang>
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.
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) :
Another method uses continuation passing style (CPS) :
<lang ocaml>let print f = f ()
<syntaxhighlight lang="ocaml">let print f = f ()
let arg value () cont = cont (Format.printf "%s\n" value)
let arg value () cont = cont (Format.printf "%s\n" value)
let stop a = a
let stop a = a
Line 2,126: Line 2,126:


let () =
let () =
print !"hello" !"hi" !"its" !"me" stop</lang>
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>.
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>).
Other example (sequential composition or Lisp-like <code>apply</code>).
<lang ocaml>type ('f,'g) t =
<syntaxhighlight lang="ocaml">type ('f,'g) t =
| Z : ('f,'f) t
| Z : ('f,'f) t
| S : 'a -> (('a -> 'f), ('f,'g) t -> 'g) t
| S : 'a -> (('a -> 'f), ('f,'g) t -> 'g) t
Line 2,143: Line 2,143:


(* top level *)
(* top level *)
# apply List.map !(fun x -> x+1) ![1;2;3] Z</lang>
# apply List.map !(fun x -> x+1) ![1;2;3] Z</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 2,150: Line 2,150:


For instance :
For instance :
<lang Oforth>: sumNum(n) | i | 0 n loop: i [ + ] ;</lang>
<syntaxhighlight lang="oforth">: sumNum(n) | i | 0 n loop: i [ + ] ;</syntaxhighlight>


{{out}}
{{out}}
Line 2,164: Line 2,164:
=={{header|Oz}}==
=={{header|Oz}}==
This is only possible for methods, not for functions/procedures.
This is only possible for methods, not for functions/procedures.
<lang oz>declare
<syntaxhighlight lang="oz">declare
class Demo from BaseObject
class Demo from BaseObject
meth test(...)=Msg
meth test(...)=Msg
Line 2,175: Line 2,175:
in
in
{D test(1 2 3 4)}
{D test(1 2 3 4)}
{D Constructed}</lang>
{D Constructed}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Line 2,181: Line 2,181:


{{Works with|PARI/GP|2.8+}}
{{Works with|PARI/GP|2.8+}}
<lang parigp>f(a[..])=for(i=1,#a,print(a[i]))</lang>
<syntaxhighlight lang="parigp">f(a[..])=for(i=1,#a,print(a[i]))</syntaxhighlight>


{{Works with|PARI/GP|2.8.1+}}
{{Works with|PARI/GP|2.8.1+}}
<lang parigp>call(f, v)</lang>
<syntaxhighlight lang="parigp">call(f, v)</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 2,194: Line 2,194:
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.
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.


<lang perl>sub print_all {
<syntaxhighlight lang="perl">sub print_all {
foreach (@_) {
foreach (@_) {
print "$_\n";
print "$_\n";
}
}
}</lang>
}</syntaxhighlight>


This function can be called with any number of arguments:
This function can be called with any number of arguments:
<lang perl>print_all(4, 3, 5, 6, 4, 3);
<syntaxhighlight lang="perl">print_all(4, 3, 5, 6, 4, 3);
print_all(4, 3, 5);
print_all(4, 3, 5);
print_all("Rosetta", "Code", "Is", "Awesome!");</lang>
print_all("Rosetta", "Code", "Is", "Awesome!");</syntaxhighlight>


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:
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:
<lang perl>@args = ("Rosetta", "Code", "Is", "Awesome!");
<syntaxhighlight lang="perl">@args = ("Rosetta", "Code", "Is", "Awesome!");
print_all(@args);</lang>
print_all(@args);</syntaxhighlight>


Introduced '''experimentally''' in 5.20.0, subroutines can have signatures when the feature is turned on:
Introduced '''experimentally''' in 5.20.0, subroutines can have signatures when the feature is turned on:
<lang perl>use 5.020;
<syntaxhighlight lang="perl">use 5.020;
use experimental 'signatures';</lang>
use experimental 'signatures';</syntaxhighlight>
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'').
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:
Functions can be declared with fixed arity:
<lang perl>sub print ($x, $y) {
<syntaxhighlight lang="perl">sub print ($x, $y) {
say $x, "\n", $y;
say $x, "\n", $y;
}</lang>
}</syntaxhighlight>


But this can easily be converted to a variadic function with a slurpy parameter:
But this can easily be converted to a variadic function with a slurpy parameter:
<lang perl>sub print_many ($first, $second, @rest) {
<syntaxhighlight lang="perl">sub print_many ($first, $second, @rest) {
say "First: $first\n"
say "First: $first\n"
."Second: $second\n"
."Second: $second\n"
."And the rest: "
."And the rest: "
. join("\n", @rest);
. join("\n", @rest);
}</lang>
}</syntaxhighlight>
It is valid for the @rest array to be empty, so this is also an optional parameter (see [[Optional parameters]]).
It is valid for the @rest array to be empty, so this is also an optional parameter (see [[Optional parameters]]).


Line 2,231: Line 2,231:
{{libheader|Phix/basics}}
{{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.
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.
<!--<lang Phix>-->
<!--<syntaxhighlight lang="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;">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>
<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,238: Line 2,238:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>def varfunc
<syntaxhighlight lang="phixmonti">def varfunc
1 tolist flatten
1 tolist flatten
len for
len for
Line 2,249: Line 2,249:




"Mary" "had" "a" "little" "lamb" 5 tolist varfunc</lang>
"Mary" "had" "a" "little" "lamb" 5 tolist varfunc</syntaxhighlight>


=={{header|PHP}}==
=={{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.
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.
<lang php><?php
<syntaxhighlight lang="php"><?php
function printAll() {
function printAll() {
foreach (func_get_args() as $x) // first way
foreach (func_get_args() as $x) // first way
Line 2,265: Line 2,265:
printAll(4, 3, 5);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!");
printAll("Rosetta", "Code", "Is", "Awesome!");
?></lang>
?></syntaxhighlight>


You can use the <tt>call_user_func_array</tt> function to apply it to a list of arguments:
You can use the <tt>call_user_func_array</tt> function to apply it to a list of arguments:
<lang php><?php
<syntaxhighlight lang="php"><?php
$args = array("Rosetta", "Code", "Is", "Awesome!");
$args = array("Rosetta", "Code", "Is", "Awesome!");
call_user_func_array('printAll', $args);
call_user_func_array('printAll', $args);
?></lang>
?></syntaxhighlight>


{{works with|PHP|5.6+}}
{{works with|PHP|5.6+}}
You can receive variable arguments in a list by having a parameter preceded by <tt>...</tt>:
You can receive variable arguments in a list by having a parameter preceded by <tt>...</tt>:
<lang php><?php
<syntaxhighlight lang="php"><?php
function printAll(...$things) {
function printAll(...$things) {
foreach ($things as $x)
foreach ($things as $x)
Line 2,283: Line 2,283:
printAll(4, 3, 5);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!");
printAll("Rosetta", "Code", "Is", "Awesome!");
?></lang>
?></syntaxhighlight>


You can use the same <tt>...</tt> syntax to supply a list of arguments to a function:
You can use the same <tt>...</tt> syntax to supply a list of arguments to a function:
<lang php><?php
<syntaxhighlight lang="php"><?php
$args = ["Rosetta", "Code", "Is", "Awesome!"];
$args = ["Rosetta", "Code", "Is", "Awesome!"];
printAll(...$args);
printAll(...$args);
?></lang>
?></syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Line 2,298: Line 2,298:
'[http://software-lab.de/doc/refA.html#arg arg]' and
'[http://software-lab.de/doc/refA.html#arg arg]' and
'[http://software-lab.de/doc/refR.html#rest rest]' functions.
'[http://software-lab.de/doc/refR.html#rest rest]' functions.
<lang PicoLisp>(de varargs @
<syntaxhighlight lang="picolisp">(de varargs @
(while (args)
(while (args)
(println (next)) ) )</lang>
(println (next)) ) )</syntaxhighlight>
The '@' operator may be used in combination with normal parameters:
The '@' operator may be used in combination with normal parameters:
<lang PicoLisp>(de varargs (Arg1 Arg2 . @)
<syntaxhighlight lang="picolisp">(de varargs (Arg1 Arg2 . @)
(println Arg1)
(println Arg1)
(println Arg2)
(println Arg2)
(while (args)
(while (args)
(println (next)) ) )</lang>
(println (next)) ) )</syntaxhighlight>
It is called like any other function
It is called like any other function
<lang PicoLisp>(varargs 'a 123 '(d e f) "hello")</lang>
<syntaxhighlight lang="picolisp">(varargs 'a 123 '(d e f) "hello")</syntaxhighlight>
also by possibly applying it to a ready-made list
also by possibly applying it to a ready-made list
<lang PicoLisp>(apply varargs '(a 123 (d e f) "hello"))</lang>
<syntaxhighlight lang="picolisp">(apply varargs '(a 123 (d e f) "hello"))</syntaxhighlight>
Output in all cases:
Output in all cases:
<pre>a
<pre>a
Line 2,318: Line 2,318:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>/* PL/I permits optional arguments, but not an infinitely varying */
<syntaxhighlight lang="pli">/* PL/I permits optional arguments, but not an infinitely varying */
/* argument list: */
/* argument list: */
s: procedure (a, b, c, d);
s: procedure (a, b, c, d);
Line 2,326: Line 2,326:
if ^omitted(c) then put skip list (c);
if ^omitted(c) then put skip list (c);
if ^omitted(d) then put skip list (d);
if ^omitted(d) then put skip list (d);
end s;</lang>
end s;</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>function print_all {
<syntaxhighlight lang="powershell">function print_all {
foreach ($x in $args) {
foreach ($x in $args) {
Write-Host $x
Write-Host $x
}
}
}</lang>
}</syntaxhighlight>
Normal usage of the function just uses all arguments one after another:
Normal usage of the function just uses all arguments one after another:
<lang powershell>print_all 1 2 'foo'</lang>
<syntaxhighlight lang="powershell">print_all 1 2 'foo'</syntaxhighlight>
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:
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:
<lang powershell>$array = 1,2,'foo'
<syntaxhighlight lang="powershell">$array = 1,2,'foo'
Invoke-Expression "& print_all $array"</lang>
Invoke-Expression "& print_all $array"</syntaxhighlight>
PowerShell v2 introduced the splat operator which makes this easier:
PowerShell v2 introduced the splat operator which makes this easier:


{{works with|PowerShell|2}}
{{works with|PowerShell|2}}
<lang powershell>print_all @array</lang>
<syntaxhighlight lang="powershell">print_all @array</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 2,365: Line 2,365:
lists are often used instead of comma-lists to handle situations where
lists are often used instead of comma-lists to handle situations where
vararg-behavior is wanted. For example:
vararg-behavior is wanted. For example:
<lang prolog>printAll( List ) :- forall( member(X,List), (write(X), nl)).
<syntaxhighlight 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.
To handle more esoteric situations, we could define a higher-order predicate to handle terms of arbitrary arity, e.g.
<lang prolog>
<syntaxhighlight lang="prolog">
execute( Term ) :-
execute( Term ) :-
Term =.. [F | Args],
Term =.. [F | Args],
forall( member(X,Args), (G =.. [F,X], G, nl) ).
forall( member(X,Args), (G =.. [F,X], G, nl) ).
</syntaxhighlight>
</lang>
<pre>
<pre>
?- execute( write(1,2,3) ).
?- execute( write(1,2,3) ).
Line 2,383: Line 2,383:
Putting <tt>*</tt> before an argument will take in any number of arguments and put them all in a tuple with the given name.
Putting <tt>*</tt> before an argument will take in any number of arguments and put them all in a tuple with the given name.


<lang python>def print_all(*things):
<syntaxhighlight lang="python">def print_all(*things):
for x in things:
for x in things:
print x</lang>
print x</syntaxhighlight>


This function can be called with any number of arguments:
This function can be called with any number of arguments:
<lang python>print_all(4, 3, 5, 6, 4, 3)
<syntaxhighlight lang="python">print_all(4, 3, 5, 6, 4, 3)
print_all(4, 3, 5)
print_all(4, 3, 5)
print_all("Rosetta", "Code", "Is", "Awesome!")</lang>
print_all("Rosetta", "Code", "Is", "Awesome!")</syntaxhighlight>


You can use the same "*" syntax to apply the function to an existing list of arguments:
You can use the same "*" syntax to apply the function to an existing list of arguments:
<lang python>args = ["Rosetta", "Code", "Is", "Awesome!"]
<syntaxhighlight lang="python">args = ["Rosetta", "Code", "Is", "Awesome!"]
print_all(*args)</lang>
print_all(*args)</syntaxhighlight>


===Keyword arguments ===
===Keyword arguments ===
Python also has keyword arguments were you can add arbitrary ''func('''''keyword1=value1, keyword2=value2 ...''''')'' keyword-value pairs when calling a function.
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.
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.
<lang python>>>> def printargs(*positionalargs, **keywordargs):
<syntaxhighlight lang="python">>>> def printargs(*positionalargs, **keywordargs):
print "POSITIONAL ARGS:\n " + "\n ".join(repr(x) for x in positionalargs)
print "POSITIONAL ARGS:\n " + "\n ".join(repr(x) for x in positionalargs)
print "KEYWORD ARGS:\n " + '\n '.join(
print "KEYWORD ARGS:\n " + '\n '.join(
Line 2,423: Line 2,423:
'fee' = 'fi'
'fee' = 'fi'
'fo' = 'fum'
'fo' = 'fum'
>>></lang>
>>></syntaxhighlight>


See the Python entry in [[Named_Arguments#Python|Named Arguments]] for a more comprehensive description of Python function parameters and call arguments.
See the Python entry in [[Named_Arguments#Python|Named Arguments]] for a more comprehensive description of Python function parameters and call arguments.
Line 2,432: Line 2,432:
puts all arguments into a list.
puts all arguments into a list.


<syntaxhighlight lang="qi">
<lang qi>
(define varargs-func
(define varargs-func
A -> (print A))
A -> (print A))
Line 2,441: Line 2,441:


(sugar in varargs 1)
(sugar in varargs 1)
</syntaxhighlight>
</lang>


=={{header|Quackery}}==
=={{header|Quackery}}==
Line 2,449: Line 2,449:
(<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.)
(<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.)


<lang Quackery>[ pack witheach
<syntaxhighlight lang="quackery">[ pack witheach
[ echo$ cr ] ] is counted-echo$ ( $ ... n --> )
[ echo$ cr ] ] is counted-echo$ ( $ ... n --> )


Line 2,466: Line 2,466:
$ "this" $ "is" $ "a" $ "formica" $ "table" 5 counted-echo$
$ "this" $ "is" $ "a" $ "formica" $ "table" 5 counted-echo$
cr
cr
marker $ "green" $ "is" $ "its" $ "colour" markered-echo$</lang>
marker $ "green" $ "is" $ "its" $ "colour" markered-echo$</syntaxhighlight>


{{out}}
{{out}}
Line 2,484: Line 2,484:
=={{header|R}}==
=={{header|R}}==
This first function, almost completes the task, but the formatting isn't quite as specified.
This first function, almost completes the task, but the formatting isn't quite as specified.
<lang rsplus> printallargs1 <- function(...) list(...)
<syntaxhighlight lang="rsplus"> printallargs1 <- function(...) list(...)
printallargs1(1:5, "abc", TRUE)
printallargs1(1:5, "abc", TRUE)
# [[1]]
# [[1]]
Line 2,493: Line 2,493:
#
#
# [[3]]
# [[3]]
# [1] TRUE</lang>
# [1] TRUE</syntaxhighlight>
This function is corrrect, though a little longer.
This function is corrrect, though a little longer.
<lang rsplus> printallargs2 <- function(...)
<syntaxhighlight lang="rsplus"> printallargs2 <- function(...)
{
{
args <- list(...)
args <- list(...)
Line 2,504: Line 2,504:
# [1] 1 2 3 4 5
# [1] 1 2 3 4 5
# [1] "abc"
# [1] "abc"
# [1] TRUE</lang>
# [1] TRUE</syntaxhighlight>
Use do.call to call a function with a list of arguments.
Use do.call to call a function with a list of arguments.
<lang rsplus>arglist <- list(x=runif(10), trim=0.1, na.rm=TRUE)
<syntaxhighlight lang="rsplus">arglist <- list(x=runif(10), trim=0.1, na.rm=TRUE)
do.call(mean, arglist)</lang>
do.call(mean, arglist)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 2,514: Line 2,514:
function called "vfun".
function called "vfun".


<syntaxhighlight lang="racket">
<lang Racket>
-> (define (vfun . xs) (for-each displayln xs))
-> (define (vfun . xs) (for-each displayln xs))
-> (vfun)
-> (vfun)
Line 2,530: Line 2,530:
13
13
14
14
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,538: Line 2,538:
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.
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.


<lang perl6>sub foo {
<syntaxhighlight lang="raku" line>sub foo {
.say for @_;
.say for @_;
say .key, ': ', .value for %_;
say .key, ': ', .value for %_;
Line 2,544: Line 2,544:


foo 1, 2, command => 'buckle my shoe',
foo 1, 2, command => 'buckle my shoe',
3, 4, order => 'knock at the door';</lang>
3, 4, order => 'knock at the door';</syntaxhighlight>


This prints:
This prints:
Line 2,557: Line 2,557:
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:
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:


<lang perl6>sub foo (*@positional, *%named) {
<syntaxhighlight lang="raku" line>sub foo (*@positional, *%named) {
.say for @positional;
.say for @positional;
say .key, ': ', .value for %named;
say .key, ': ', .value for %named;
}</lang>
}</syntaxhighlight>


Unlike in Perl 5, arrays and hashes aren't flattened automatically. Use the <code>|</code> operator to flatten:
Unlike in Perl 5, arrays and hashes aren't flattened automatically. Use the <code>|</code> operator to flatten:


<lang perl6>foo |@ary, |%hsh;</lang>
<syntaxhighlight lang="raku" line>foo |@ary, |%hsh;</syntaxhighlight>


=={{header|RapidQ}}==
=={{header|RapidQ}}==
RapidQ uses special keywords SUBI and FUNCTIONI for procedures and functions with variable number of parameters.
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$.
Numeric parameters are accessed from array ParamVal and string parameters from array ParamStr$.
<lang rapidq>SUBI printAll (...)
<syntaxhighlight lang="rapidq">SUBI printAll (...)
FOR i = 1 TO ParamValCount
FOR i = 1 TO ParamValCount
PRINT ParamVal(i)
PRINT ParamVal(i)
Line 2,580: Line 2,580:
printAll 4, 3, 5, 6, 4, 3
printAll 4, 3, 5, 6, 4, 3
printAll 4, 3, 5
printAll 4, 3, 5
printAll "Rosetta", "Code", "Is", "Awesome!"</lang>
printAll "Rosetta", "Code", "Is", "Awesome!"</syntaxhighlight>


=={{header|REALbasic}}==
=={{header|REALbasic}}==
Line 2,586: Line 2,586:
This subroutine prints it arguments. ParamArrays must be the last argument but may be preceded by any number of normal arguments.
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)
Sub PrintArgs(ParamArray Args() As String)
For i As Integer = 0 To Ubound(Args)
For i As Integer = 0 To Ubound(Args)
Line 2,592: Line 2,592:
Next
Next
End Sub
End Sub
</syntaxhighlight>
</lang>


Calling the subroutine.
Calling the subroutine.
<syntaxhighlight lang="vb">
<lang vb>
PrintArgs("Hello", "World!", "Googbye", "World!")
PrintArgs("Hello", "World!", "Googbye", "World!")
</syntaxhighlight>
</lang>


=={{header|REBOL}}==
=={{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:
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:
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Variadic Arguments"
Title: "Variadic Arguments"
]
]
Line 2,612: Line 2,612:
]
]


print-all [rebol works this way]</lang>
print-all [rebol works this way]</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===simplistic===
===simplistic===
<lang rexx>print_all: procedure /* [↓] is the # of args passed.*/
<syntaxhighlight lang="rexx">print_all: procedure /* [↓] is the # of args passed.*/
do j=1 for arg()
do j=1 for arg()
say arg(j)
say arg(j)
end /*j*/
end /*j*/
return</lang>
return</syntaxhighlight>


===annotated===
===annotated===
<lang rexx>print_all: procedure /* [↓] is the # of args passed.*/
<syntaxhighlight lang="rexx">print_all: procedure /* [↓] is the # of args passed.*/
do j=1 for arg()
do j=1 for arg()
say '[argument' j"]: " arg(j)
say '[argument' j"]: " arg(j)
end /*j*/
end /*j*/
return</lang>
return</syntaxhighlight>


===invocations===
===invocations===
The function can be called with any number of arguments (including no arguments and/or omitted arguments),
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.
<br>although some REXX implementations impose a limit and the number of arguments.
<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'
<syntaxhighlight 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,",
call print_all "One ringy-dingy,",
Line 2,641: Line 2,641:
"(Lily Tomlin routine)"
"(Lily Tomlin routine)"


/* [↑] example showing multi-line arguments.*/</lang>
/* [↑] example showing multi-line arguments.*/</syntaxhighlight>
===dynamically built argument list===
===dynamically built argument list===
<lang rexx>/* REXX */
<syntaxhighlight lang="rexx">/* REXX */
list=''
list=''
Do i=1 To 6
Do i=1 To 6
Line 2,655: Line 2,655:
say arg(j)
say arg(j)
end /*j*/
end /*j*/
return</lang>
return</syntaxhighlight>
Output:
Output:
<pre>arg1
<pre>arg1
Line 2,666: Line 2,666:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Variadic function
# Project : Variadic function


Line 2,690: Line 2,690:
svect = left(svect, len(svect) - 1)
svect = left(svect, len(svect) - 1)
see "" + svect + "]"
see "" + svect + "]"
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,700: Line 2,700:
=={{header|Ruby}}==
=={{header|Ruby}}==
The * is sometimes referred to as the "splat" in Ruby.
The * is sometimes referred to as the "splat" in Ruby.
<lang ruby>def print_all(*things)
<syntaxhighlight lang="ruby">def print_all(*things)
puts things
puts things
end</lang>
end</syntaxhighlight>


This function can be called with any number of arguments:
This function can be called with any number of arguments:
<lang ruby>print_all(4, 3, 5, 6, 4, 3)
<syntaxhighlight lang="ruby">print_all(4, 3, 5, 6, 4, 3)
print_all(4, 3, 5)
print_all(4, 3, 5)
print_all("Rosetta", "Code", "Is", "Awesome!")</lang>
print_all("Rosetta", "Code", "Is", "Awesome!")</syntaxhighlight>


You can use the same "*" syntax to apply the function to an existing list of arguments:
You can use the same "*" syntax to apply the function to an existing list of arguments:
<lang ruby>args = ["Rosetta", "Code", "Is", "Awesome!"]
<syntaxhighlight lang="ruby">args = ["Rosetta", "Code", "Is", "Awesome!"]
print_all(*args)</lang>
print_all(*args)</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>// 20220106 Rust programming solution
<syntaxhighlight lang="rust">// 20220106 Rust programming solution


macro_rules! print_all {
macro_rules! print_all {
Line 2,722: Line 2,722:
fn main() {
fn main() {
print_all!("Rosetta", "Code", "Is", "Awesome!");
print_all!("Rosetta", "Code", "Is", "Awesome!");
}</lang>
}</syntaxhighlight>
Output: [https://tio.run/##PYy9CoMwAIT3PMUpDokIWocOlRZKp66@gIQ2lUB@JIm0IHn2VCt0uYPj@87NPqRU12ibtm0OzRH9umBydnRca2lGeKvmIK0hRPOHs4OblfDZikgTBq4UFgKAFrTgbvQn8Zkcq0qG8wULCrqDymQ0X2Je4UexDqxEBImEvAw0l4ay/ej/uwq99SIEvlr5zT7F1ne/5fUtvNUiy1lHYkpf Try it online!]
Output: [https://tio.run/##PYy9CoMwAIT3PMUpDokIWocOlRZKp66@gIQ2lUB@JIm0IHn2VCt0uYPj@87NPqRU12ibtm0OzRH9umBydnRca2lGeKvmIK0hRPOHs4OblfDZikgTBq4UFgKAFrTgbvQn8Zkcq0qG8wULCrqDymQ0X2Je4UexDqxEBImEvAw0l4ay/ej/uwq99SIEvlr5zT7F1ne/5fUtvNUiy1lHYkpf Try it online!]


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>def printAll(args: Any*) = args foreach println</lang>
<syntaxhighlight lang="scala">def printAll(args: Any*) = args foreach println</syntaxhighlight>


Example:
Example:
Line 2,752: Line 2,752:
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.
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.


<lang scheme>(define (print-all . things)
<syntaxhighlight lang="scheme">(define (print-all . things)
(for-each
(for-each
(lambda (x) (display x) (newline))
(lambda (x) (display x) (newline))
things))</lang>
things))</syntaxhighlight>


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


<lang scheme>(define print-all
<syntaxhighlight lang="scheme">(define print-all
(lambda things
(lambda things
(for-each
(for-each
(lambda (x) (display x) (newline))
(lambda (x) (display x) (newline))
things)))</lang>
things)))</syntaxhighlight>


This function can be called with any number of arguments:
This function can be called with any number of arguments:
<lang scheme>(print-all 4 3 5 6 4 3)
<syntaxhighlight lang="scheme">(print-all 4 3 5 6 4 3)
(print-all 4 3 5)
(print-all 4 3 5)
(print-all "Rosetta" "Code" "Is" "Awesome!")</lang>
(print-all "Rosetta" "Code" "Is" "Awesome!")</syntaxhighlight>


The <tt>apply</tt> function will apply the function to a list of arguments:
The <tt>apply</tt> function will apply the function to a list of arguments:
<lang scheme>(define args '("Rosetta" "Code" "Is" "Awesome!"))
<syntaxhighlight lang="scheme">(define args '("Rosetta" "Code" "Is" "Awesome!"))
(apply print-all args)</lang>
(apply print-all args)</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
A parameter declared with "*", can take any number of arguments of any type.
A parameter declared with "*", can take any number of arguments of any type.
<lang ruby>func print_all(*things) {
<syntaxhighlight lang="ruby">func print_all(*things) {
things.each { |x| say x };
things.each { |x| say x };
}</lang>
}</syntaxhighlight>
This function can be called with any number of arguments:
This function can be called with any number of arguments:
<lang ruby>print_all(4, 3, 5, 6, 4, 3);
<syntaxhighlight lang="ruby">print_all(4, 3, 5, 6, 4, 3);
print_all(4, 3, 5);
print_all(4, 3, 5);
print_all("Rosetta", "Code", "Is", "Awesome!");</lang>
print_all("Rosetta", "Code", "Is", "Awesome!");</syntaxhighlight>
Also, there is "..." which transforms an array into a list of arguments.
Also, there is "..." which transforms an array into a list of arguments.
<lang ruby>var args = ["Rosetta", "Code", "Is", "Awesome!"];
<syntaxhighlight lang="ruby">var args = ["Rosetta", "Code", "Is", "Awesome!"];
print_all(args...);</lang>
print_all(args...);</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
Line 2,791: Line 2,791:
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.
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.


<lang slate>define: #printAll -> [| *rest | rest do: [| :arg | inform: arg printString]].
<syntaxhighlight lang="slate">define: #printAll -> [| *rest | rest do: [| :arg | inform: arg printString]].


printAll applyTo: #(4 3 5 6 4 3).
printAll applyTo: #(4 3 5 6 4 3).
printAll applyTo: #('Rosetta' 'Code' 'Is' 'Awesome!').</lang>
printAll applyTo: #('Rosetta' 'Code' 'Is' 'Awesome!').</syntaxhighlight>


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>):
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>):
<lang slate>_@lobby printAll [| *rest | rest do: [| :arg | inform: arg printString]].
<syntaxhighlight lang="slate">_@lobby printAll [| *rest | rest do: [| :arg | inform: arg printString]].
lobby printAll, 4, 3, 5, 6, 4, 3.
lobby printAll, 4, 3, 5, 6, 4, 3.
lobby printAll, 'Rosetta', 'Code', 'Is', 'Awesome!'.
lobby printAll, 'Rosetta', 'Code', 'Is', 'Awesome!'.
</syntaxhighlight>
</lang>


=={{header|Swift}}==
=={{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.
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.
<lang swift>func printAll<T>(things: T...) {
<syntaxhighlight lang="swift">func printAll<T>(things: T...) {
// "things" is a [T]
// "things" is a [T]
for i in things {
for i in things {
print(i)
print(i)
}
}
}</lang>
}</syntaxhighlight>
This function can be called with any number of arguments:
This function can be called with any number of arguments:
<lang swift>printAll(4, 3, 5, 6, 4, 3)
<syntaxhighlight lang="swift">printAll(4, 3, 5, 6, 4, 3)
printAll(4, 3, 5)
printAll(4, 3, 5)
printAll("Rosetta", "Code", "Is", "Awesome!")</lang>
printAll("Rosetta", "Code", "Is", "Awesome!")</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}
If the last argument is named "args", it collects all the remaining arguments
If the last argument is named "args", it collects all the remaining arguments
<lang tcl>proc print_all {args} {puts [join $args \n]}
<syntaxhighlight lang="tcl">proc print_all {args} {puts [join $args \n]}


print_all 4 3 5 6 4 3
print_all 4 3 5 6 4 3
Line 2,827: Line 2,827:


print_all $things ;# ==> incorrect: passes a single argument (a list) to print_all
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</lang>
print_all {*}$things ;# ==> correct: passes each element of the list to the procedure</syntaxhighlight>
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:
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:
<lang Tcl>eval [list print_all] [lrange $things 0 end]</lang>
<syntaxhighlight lang="tcl">eval [list print_all] [lrange $things 0 end]</syntaxhighlight>


=={{header|TIScript}}==
=={{header|TIScript}}==
Line 2,835: Line 2,835:
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.
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.


<lang javascript>
<syntaxhighlight lang="javascript">
function printAll(separator,argv..) {
function printAll(separator,argv..) {
if(argv.length)
if(argv.length)
Line 2,844: Line 2,844:
printAll(" ", 4, 3, 5, 6, 4, 3);
printAll(" ", 4, 3, 5, 6, 4, 3);
printAll(",", 4, 3, 5);
printAll(",", 4, 3, 5);
printAll("! ","Rosetta", "Code", "Is", "Awesome");</lang>
printAll("! ","Rosetta", "Code", "Is", "Awesome");</syntaxhighlight>


=={{header|uBasic/4tH}}==
=={{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.
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.
<lang>Push _Mary, _had, _a, _little, _lamb ' Push the hashes
<syntaxhighlight lang="text">Push _Mary, _had, _a, _little, _lamb ' Push the hashes
Proc _PrintStrings (5) ' Print the string
Proc _PrintStrings (5) ' Print the string


Line 2,890: Line 2,890:
_a Print "a"; : Return
_a Print "a"; : Return
_little Print "little"; : Return
_little Print "little"; : Return
_lamb Print "lamb"; : Return</lang>
_lamb Print "lamb"; : Return</syntaxhighlight>
{{out}}
{{out}}
<pre>Mary had a little lamb
<pre>Mary had a little lamb
Line 2,901: Line 2,901:


=={{header|Ursala}}==
=={{header|Ursala}}==
<lang Ursala>f = %gP*=
<syntaxhighlight lang="ursala">f = %gP*=


#show+
#show+


main = f <'foo',12.5,('x','y'),100></lang>
main = f <'foo',12.5,('x','y'),100></syntaxhighlight>
<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.
<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,920: Line 2,920:
Using a count as the indication of number of arguments to extract,
Using a count as the indication of number of arguments to extract,


<lang v>[myfn
<syntaxhighlight lang="v">[myfn
[zero? not] [swap puts pred]
[zero? not] [swap puts pred]
while
while
].
].


100 200 300 400 500 3 myfn</lang>
100 200 300 400 500 3 myfn</syntaxhighlight>
results in:
results in:
<lang v>500
<syntaxhighlight lang="v">500
400
400
300</lang>
300</syntaxhighlight>


=={{header|Visual Basic}}==
=={{header|Visual Basic}}==
{{works with|Visual Basic|6}}
{{works with|Visual Basic|6}}
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit
'--------------------------------------------------
'--------------------------------------------------
Sub varargs(ParamArray a())
Sub varargs(ParamArray a())
Line 2,972: Line 2,972:
varargs v(2), v(1), v(0), 11
varargs v(2), v(1), v(0), 11
End Sub</lang>
End Sub</syntaxhighlight>
{{out}}
{{out}}
<pre>call 1
<pre>call 1
Line 3,000: Line 3,000:


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>fn print_all(things ...string) {
<syntaxhighlight lang="vlang">fn print_all(things ...string) {
for x in things {
for x in things {
println(x)
println(x)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Vorpal}}==
=={{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.
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.
<lang vorpal>self.f = method(x, y[ ], z){
<syntaxhighlight lang="vorpal">self.f = method(x, y[ ], z){
x.print()
x.print()
for(i = 0, i < y.size(), i = i + 1){
for(i = 0, i < y.size(), i = i + 1){
Line 3,020: Line 3,020:
self.f(1, 2, 3, 4)
self.f(1, 2, 3, 4)
'---'.print()
'---'.print()
self.f(1, 2)</lang>
self.f(1, 2)</syntaxhighlight>


=={{header|Wren}}==
=={{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.
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.
<lang ecmascript>var printArgs = Fn.new { |args| args.each { |arg| System.print(arg) } }
<syntaxhighlight lang="ecmascript">var printArgs = Fn.new { |args| args.each { |arg| System.print(arg) } }


printArgs.call(["Mary", "had", "3", "little", "lambs"])</lang>
printArgs.call(["Mary", "had", "3", "little", "lambs"])</syntaxhighlight>


{{out}}
{{out}}
Line 3,038: Line 3,038:


=={{header|XLISP}}==
=={{header|XLISP}}==
<lang lisp>(defun print-on-separate-lines (&rest xs)
<syntaxhighlight lang="lisp">(defun print-on-separate-lines (&rest xs)
(for-each print xs))
(for-each print xs))


Line 3,051: Line 3,051:
; and then call APPLY:
; and then call APPLY:


(apply print-on-separate-lines test)</lang>
(apply print-on-separate-lines test)</syntaxhighlight>
{{out}}
{{out}}
<pre>I
<pre>I
Line 3,082: Line 3,082:
=={{header|XPL0}}==
=={{header|XPL0}}==
Passing an array is probably a better way to accomplish this task.
Passing an array is probably a better way to accomplish this task.
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
def IntSize=4; \number of bytes in an integer
def IntSize=4; \number of bytes in an integer


Line 3,093: Line 3,093:
];
];


Var(4, "Mary", "had", "a", "little")</lang>
Var(4, "Mary", "had", "a", "little")</syntaxhighlight>


Output:
Output:
Line 3,105: Line 3,105:
=={{header|zkl}}==
=={{header|zkl}}==
In zkl, all functions and methods are variadic (they are just passed a list).
In zkl, all functions and methods are variadic (they are just passed a list).
<lang zkl>fcn f{vm.arglist.apply2("println")}
<syntaxhighlight lang="zkl">fcn f{vm.arglist.apply2("println")}
f("Mary","had","a","little");</lang>
f("Mary","had","a","little");</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 3,114: Line 3,114:
little
little
</pre>
</pre>
<lang zkl>a:="This is a test".split(); //-->L("This","is","a","test")
<syntaxhighlight 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</lang>
f(a.xplode()); // xplode takes a list and blows it apart into call args</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 3,123: Line 3,123:
test
test
</pre>
</pre>
<lang zkl>fcn g{f(vm.pasteArgs(2)}
<syntaxhighlight lang="zkl">fcn g{f(vm.pasteArgs(2)}
g(a.xplode());</lang>
g(a.xplode());</syntaxhighlight>
pasteArgs takes the passed in function args and stuffs them back into the arglist of the function call
pasteArgs takes the passed in function args and stuffs them back into the arglist of the function call
{{output}}
{{output}}