From 931a9947d0d59f52d51109f3bdd7b89ea513c0aa Mon Sep 17 00:00:00 2001 From: Tim Holy Date: Mon, 20 Apr 2015 10:40:06 -0500 Subject: [PATCH] Add docs and NEWS on Vararg{T,N} [ci skip] --- NEWS.md | 3 +++ doc/manual/functions.rst | 2 ++ doc/manual/methods.rst | 26 ++++++++++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/NEWS.md b/NEWS.md index c0db3c4559975..9d383686da5d2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -29,6 +29,9 @@ New language features and macros in packages and user code ([#8791]). Type `?@doc` at the repl to see the current syntax and more information. + * Varargs functions may now declare the varargs length as `x::Vararg{T,N}` to + restrict dispatch. + Language changes ---------------- diff --git a/doc/manual/functions.rst b/doc/manual/functions.rst index f6f53652b0975..4d67ea1267666 100644 --- a/doc/manual/functions.rst +++ b/doc/manual/functions.rst @@ -329,6 +329,8 @@ the zero or more values passed to ``bar`` after its first two arguments: In all these cases, ``x`` is bound to a tuple of the trailing values passed to ``bar``. +It is possible to constrain the number of values passed as a variable argument; this will be discussed later in :ref:`man-vararg-fixedlen`. + 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: diff --git a/doc/manual/methods.rst b/doc/manual/methods.rst index 91a8eeb0caa9f..28981e1fc1557 100644 --- a/doc/manual/methods.rst +++ b/doc/manual/methods.rst @@ -550,6 +550,32 @@ can also constrain type parameters of methods:: The ``same_type_numeric`` function behaves much like the ``same_type`` function defined above, but is only defined for pairs of numbers. +.. _man-vararg-fixedlen: + +Parametrically-constrained Varargs methods +------------------------------------------ + +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: + +.. doctest:: + + julia> bar(a,b,x::Vararg{Any,2}) = (a,b,x) + + julia> bar(1,2,3) + ERROR: MethodError: `bar` has no matching method bar(::Int, ::Int, ::Int) + + julia> bar(1,2,3,4) + (1,2,(3,4)) + + julia> bar(1,2,3,4,5) + ERROR: MethodError: `bar` has no method matching bar(::Int, ::Int, ::Int, ::Int, ::Int) + +More usefully, it is possible to constrain varargs methods by a parameter. For example:: + + function getindex{T,N}(A::AbstractArray{T,N}, indexes::Vararg{Number,N}) + +would be called only when the number of ``indexes`` matches the dimensionality of the array. + .. _man-note-on-optional-and-keyword-arguments: Note on Optional and keyword Arguments