Variadic function: Difference between revisions

→‎{{header|Julia}}: simplify to match the other languages, which just solve the task at hand
(new Emacs Lisp)
(→‎{{header|Julia}}: simplify to match the other languages, which just solve the task at hand)
Line 750:
 
=={{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):
It is often convenient to be able to write functions taking an arbitrary number of arguments. Such functions are traditionally known as “varargs” functions, which is short for “variable number of arguments”. You can define a varargs function by following the last argument with an ellipsis:
 
<lang julia>bar(a,b,x...) = (a,b,x)</lang>
The variables a and b are bound to the first two argument values as usual, and the variable x is bound to an iterable collection of the zero or more values passed to bar after its first two arguments:
<lang julia>
julia> print_each(X...) = for x in X; println(x); end
julia> bar(1,2)
(1,2,())
 
julia> barprint_each(1,2 "hello",3 23.4)
1
(1,2,(3,))
hello
 
23.4
julia> bar(1,2,3,4)
</lang julia>
(1,2,(3,4))
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:
 
julia> bar(1,2,3,4,5,6)
(1,2,(3,4,5,6))</lang>
In all these cases, x is bound to a tuple of the trailing values passed to bar.
 
On the flip side, it is often handy to “splice” the values contained in an iterable collection into a function call as individual arguments. To do this, one also uses ... but in the function call instead:
<lang julia>
julia> xargs = [ "first", (31,42,17), "last" ]
3-element Int64 Array{Any,1}:
(3,4)
"first"
 
julia> bar (1,2,x...17)
"last
(1,2,(3,4))</lang>
In this case a tuple of values is spliced into a varargs call precisely where the variable number of arguments go. This need not be the case, however:
<lang julia>
julia> x = (2,3,4)
(2,3,4)
 
julia> bar(1,x...)
(1,2,(3,4))
 
julia> x = (1,2,3,4)
(1,2,3,4)
 
julia> bar(x...)
(1,2,(3,4))</lang>
Furthermore, the iterable object spliced into a function call need not be a tuple:
<lang julia>
julia> x = [3,4]
2-element Int64 Array:
3
4
 
julia> bar(1,2,x...)
(1,2,(3,4))
 
julia> x = [1,2,3,4]
4-element Int64 Array:
1
2
3
4
 
julia> bar(x...)
(1,2,(3,4))</lang>
Also, the function that arguments are spliced into need not be a varargs function (although it often is):
<lang julia>
baz(a,b) = a + b
 
julia> args = [1,2]
2-element Int64 Array:
1
2
 
julia> baz(args...)
3
 
julia> args = [1,2,3]
3-element Int64 Array:
1
2
3
 
julia> bazprint_each(args...)</lang>
first
no method baz(Int64,Int64,Int64)
(1,2,()17)
As you can see, if the wrong number of elements are in the spliced container, then the function call will fail, just as it would if too many arguments were given explicitly.
last
</lang julia>
 
=={{header|Logo}}==
Anonymous user