Estimated reading time: 2 minutes
In Julia, the ...
operator, also known as the “splat” or “ellipsis” operator, is used to unpack the contents of a collection or tuple.
Here are a few common use cases:
- Function arguments: When used in a function call, the
...
operator can be used to pass the elements of a collection or tuple as separate arguments to the function.
In the example below, we create our Tuple and then call it in the function which then prints it out.
julia> function my_function(x, y, z)
print(x,y,z)
end
my_function (generic function with 1 method)
julia> my_tuple = (1, 2, 3)
(1, 2, 3)
julia> my_function(my_tuple...)
123
2. Function definitions: The ...
operator can be used in function definitions to allow for a variable number of arguments.
As a result, in this example, the my_function gets passed five variables.
As you can see there are three … at the end of the function. What this does is then instructs the print function to print the last three integers passed inside the bracket, and leave the first two outside.
The reason for this is that the print statement prints the first two parameters passed, then as z has … after it, splits the 3rd and subsequent parameters into a Tuple.
julia> function my_function(x, y, z...)
print(x,y,z)
end
my_function (generic function with 2 methods)
julia>my_function(1, 2, 3)
12(3, 4, 5)
3. Tuple construction: The ...
operator can be used to concatenate two or more tuples into a single tuple. For example:
julia> tuple1 = (1, 2)
(1, 2)
julia> tuple2 = (3, 4)
(3, 4)
julia> tuple3 = (5, 6)
(5, 6)
julia> tuple4 = (tuple1..., tuple2..., tuple3...)
(1, 2, 3, 4, 5, 6)
4. Array construction: The ...
operator can be used to concatenate two or more arrays along a specified dimension. For example:
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> B = [5 6; 7 8]
2×2 Matrix{Int64}:
5 6
7 8
julia> C = [A B] # horizontal concatenation
2×4 Matrix{Int64}:
1 2 5 6
3 4 7 8
julia> D = [A; B] # vertical concatenation
4×2 Matrix{Int64}:
1 2
3 4
5 6
7 8
Note that the ...
operator can also be used in other contexts, such as in variable assignments, but its primary purpose is for unpacking and concatenation.