Skip to content

Commit 931a994

Browse files
committed
Add docs and NEWS on Vararg{T,N}
[ci skip]
1 parent 1d02ec4 commit 931a994

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

NEWS.md

+3
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ New language features
2929
and macros in packages and user code ([#8791]). Type `?@doc` at the repl
3030
to see the current syntax and more information.
3131

32+
* Varargs functions may now declare the varargs length as `x::Vararg{T,N}` to
33+
restrict dispatch.
34+
3235
Language changes
3336
----------------
3437

doc/manual/functions.rst

+2
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,8 @@ the zero or more values passed to ``bar`` after its first two arguments:
329329
In all these cases, ``x`` is bound to a tuple of the trailing values
330330
passed to ``bar``.
331331

332+
It is possible to constrain the number of values passed as a variable argument; this will be discussed later in :ref:`man-vararg-fixedlen`.
333+
332334
On the flip side, it is often handy to "splice" the values contained in
333335
an iterable collection into a function call as individual arguments. To
334336
do this, one also uses ``...`` but in the function call instead:

doc/manual/methods.rst

+26
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,32 @@ can also constrain type parameters of methods::
550550
The ``same_type_numeric`` function behaves much like the ``same_type``
551551
function defined above, but is only defined for pairs of numbers.
552552

553+
.. _man-vararg-fixedlen:
554+
555+
Parametrically-constrained Varargs methods
556+
------------------------------------------
557+
558+
Function parameters can also be used to constrain the number of arguments that may be supplied to a "varargs" function (:ref:`man-varargs-functions`). The notation ``Vararg{T,N}`` is used to indicate such a constraint. For example:
559+
560+
.. doctest::
561+
562+
julia> bar(a,b,x::Vararg{Any,2}) = (a,b,x)
563+
564+
julia> bar(1,2,3)
565+
ERROR: MethodError: `bar` has no matching method bar(::Int, ::Int, ::Int)
566+
567+
julia> bar(1,2,3,4)
568+
(1,2,(3,4))
569+
570+
julia> bar(1,2,3,4,5)
571+
ERROR: MethodError: `bar` has no method matching bar(::Int, ::Int, ::Int, ::Int, ::Int)
572+
573+
More usefully, it is possible to constrain varargs methods by a parameter. For example::
574+
575+
function getindex{T,N}(A::AbstractArray{T,N}, indexes::Vararg{Number,N})
576+
577+
would be called only when the number of ``indexes`` matches the dimensionality of the array.
578+
553579
.. _man-note-on-optional-and-keyword-arguments:
554580

555581
Note on Optional and keyword Arguments

0 commit comments

Comments
 (0)