When should I use a Pair over a two element Tuple and vice versa?
Mainly when you want to visually highlight, that there exists a relation between the first and second elements. For example, consider the following Dict
construction
Dict(:a => 1, :b => 2)
Despite you can use Tuple
, but it is more obvious here, that there is a relation between keys (:a
and :b
) and values (1, 2).
Actually, it is more than just obvious, it gives you the possibility to use the following definition
julia> Dict(((:a, 1) => (:b, 2)))
Dict{Tuple{Symbol, Int64}, Tuple{Symbol, Int64}} with 1 entry:
(:a, 1) => (:b, 2)
Compare it with
julia> Dict(((:a, 1), (:b, 2)))
Dict{Symbol, Int64} with 2 entries:
:a => 1
:b => 2
By using only tuples it's hard to build a dictionary that can have tuples as keys.
Another, slightly different example can be found in join
functions from DataFrames.jl
innerjoin(a, b, on = [:City => :Location, :Job => :Work])
Here it is easy to understand, that you bind City
column of a
with Location
column of b
. Though, tuple syntax would be fine, but Pair
notation looks more readable.
On the other hand, if you are building two-dimensional point there is no need in using Pair
, usual Tuple is more than enough. Point(x => y)
definition looks strange, compared to Point(x, y)
.
So, the rule of thumb, if there is a relation between the first and second element use Pair
, if they are independent of each other use Tuple
.
© 2022 - 2024 — McMap. All rights reserved.