logo

Tips for passing Optional Arguments through the Julia Splatt Operator 📂Julia

Tips for passing Optional Arguments through the Julia Splatt Operator

Overview

In Julia, the most frequently used purpose of the ... splat is explained as the method of passing optional arguments. Basically, it uses the method of applying the splat operator to the tuple after determining in advance what options to put into which arguments, in the form of a named tuple.

Code

Passing to Multiple Functions

args1 = (; dims = 1)

The named tuple args1 above can be commonly used for all functions having an optional argument called dims. In the following example, sum() and minimum() are completely different functions, but they were applied regardless of the type of function as they both have dims.

julia> sum(rand(100,100); args1...)
1×100 Matrix{Float64}:
 47.0704  45.7637  44.4513  48.2325  50.5745  51.9176  …  49.9548  47.6825  50.7284  50.0861  50.0168  50.5116

julia> minimum(rand(100,100); args1...)
1×100 Matrix{Float64}:
 0.00702003  0.0163299  0.00665818  0.0174564  0.00589048  …  0.002967  0.00460205  0.0116248  0.0114521  0.0698425

Passing Multiple Arguments

args2 = (; dims = 2, rev = true)

The named tuple args2 above includes the optional argument rev in addition to dims. In the following example, the sort() function reflected both options well and returned the computation result regardless of the input data.

julia> sort(rand(0:9, 3,3); args2...)
3×3 Matrix{Int64}:
 9  4  4
 6  5  2
 8  0  0

julia> sort(rand(3,3); args2...)
3×3 Matrix{Float64}:
 0.438682  0.211154  0.108741
 0.72113   0.445214  0.00910109
 0.971441  0.666732  0.0227372

Entire Code

args1 = (; dims = 1)
sum(rand(100,100); args1...)
minimum(rand(100,100); args1...)

args2 = (; dims = 2, rev = true)
sort(rand(0:9, 3,3); args2...)
sort(rand(3,3); args2...)

Environment

  • OS: Windows
  • julia: v1.8.3