Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Julia, why use a Pair over a two element Tuple?

When should I use a Pair over a two element Tuple and vice versa?

like image 642
Alec Avatar asked Mar 13 '21 14:03

Alec


People also ask

How to define tuple in Julia?

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.

What is a collection in Julia?

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)


Video Answer


1 Answers

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.

like image 124
Andrej Oskin Avatar answered Sep 20 '22 14:09

Andrej Oskin