When should I use a Pair over a two element Tuple and vice versa?
Tuples in Julia are an immutable collection of distinct values of same or different datatypes separated by commas. Tuples are more like arrays in Julia except that arrays only take values of similar datatypes. The values of a tuple can not be changed because tuples are immutable.
The collect() is an inbuilt function in julia which is used to return an array of all items in the specified collection or iterator. Syntax: collect(collection)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With