Julia's Splat Operator
Overview
In Julia, ...
is called the splat operator. It is usefully employed when using functions or defining arrays1. This operator isn’t exclusive to Julia, but it’s defined in a more intuitive way compared to other languages, making it exceptionally easy to learn and understand. From personal experience, using ...
seems to bring some sort of enlightenment regarding Julia programming.
Code
Function Input
Primarily, ...
is appended after an array or generator and unfolds every element from the preceding container/iterator as it appears.
julia> min([1,2,3,4,5,6,7,8,9,10])
ERROR: MethodError: no method matching min(::Vector{Int64})
julia> min(1,2,3,4,5,6,7,8,9,10)
1
For instance, Julia’s min()
function acts as a reducer, so you cannot pass an array as a whole; instead, you must directly provide multiple numbers as arguments. Naturally, as arrays grow larger, it becomes cumbersome to manually unfold and list each element, and using ...
allows for these elements to be conveniently incorporated.
julia> min(1:10)
ERROR: MethodError: no method matching min(::UnitRange{Int64})
julia> min((1:10)...)
1
Of course, there actually exists a minimum()
function that can be used on arrays, making this approach somewhat unnecessary.
Array Definition
julia> [(1:10)]
1-element Vector{UnitRange{Int64}}:
1:10
The array defined above is an array of unit ranges, which makes directly accessing elements somewhat tedious. If time permits, one could manually insert numbers from 1 to 10, but employing the splat operator allows for an easy definition like so:
julia> [(1:10)...]
10-element Vector{Int64}:
1
2
3
4
5
6
7
8
9
10
There are alternatives such as the collect()
function, but this method is appealing for its neat and ingenious representation. However, it’s not highly recommended in terms of speed, so avoid overusing ...
.
julia> [eachrow(rand(3,3))...]
3-element Vector{SubArray{Float64, 1, Matrix{Float64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
[0.6695368164913422, 0.69695509795356, 0.12084083239135612]
[0.6833475867141307, 0.5368141950494666, 0.7877252857572066]
[0.2810163716135018, 0.04317485597011517, 0.44214186775440534]
...
becomes interesting when used with generators as seen above. eachrow()
returns a generator of vectors, each corresponding to a row in the matrix. Through the splat operator, these vectors are inserted into array notation []
, creating a vector of vectors.
Full code
min([1,2,3,4,5,6,7,8,9,10])
min(1,2,3,4,5,6,7,8,9,10)
min(1:10)
min((1:10)...)
[(1:10)]
[(1:10)...]
[eachrow(rand(3,3))...]
Environment
- OS: Windows
- julia: v1.8.3