Tuesday 1 March 2016

Julia: varargs: variable number of arguments to function

Julia support function that take variable number of arguments. This feature is called varargs or variable number of arguments. Varargs are represented by ‘…’

For example, in function sum(a,b,c...), c is bound to a tuple that take variable number of arguments.

sum(1,2,3,4,5) : 1 is assigned to a, 2 is assigned to b, (3,4,5) are assigned to c as tuple.
julia> function sum(a,b,c...)
           sum=a+b
           for i in c
               sum = sum + i
           end
           return sum
       end
sum (generic function with 3 methods)

julia> sum(1,2)
3

julia> sum(1,2,3)
6

julia> sum(1,2,3,4,5)
15



Previous                                                 Next                                                 Home

No comments:

Post a Comment