Splat operator

this doesn’t work right? are you sure you’re running your function?

julia> function mysum(args...)
           sum=0
           for i in args
           sum+=i
           end
       end
mysum (generic function with 1 method)

julia> mysum([1,2,3])
ERROR: MethodError: no method matching +(::Int64, ::Vector{Int64})
For element-wise addition, use broadcasting with dot syntax: scalar .+ array
The function `+` exists, but no method is defined for this combination of argument types.

basically when you have mysum(args...), it now can take any number of arguments, like:

mysum(1,2)
mysum(1,2,3)

you can’t do that if you defined the function as mysum(args)

Right, there is definitely a difference here. Often when used in function definition form, I’d call ... the “slurp” operator as it collects all args (even 0 and 1-argument calls) into a tuple that you iterate over. If you don’t use the ... in the definition, you’d just get the argument itself (without getting plopped into a tuple) — and that value may or may not itself be iterable.

You likely have more than one method of mysum defined.

Ask yourself: When you call mysum([1,2, 3]...), where do the values end up?

From your function definition, they end up inside the variable args. And if args contains the values 1, 2, and 3, it must be a collection. And if it’s a collection, you can iterate over it.

In a function definition, args... slurps up the input values, what else could conceivably happen here?

It’s perhaps a bit confusing that the same syntax is used for slurping and splatting, perhaps one could have used ...args, for example. Note that Python does the same thing.

1 Like