`Pair{A,B}` vs. `Tuple{A,B}`

So what’s the difference between Pair{A,B} and Tuple{A,B}? Why do we have both instead of one?

1 Like

Types transport meaning. Same reason why we don’t always just use blobs of memory, even though everything boils down to that :wink:
E.g. you want to construct a pair with this syntax: a => b, but adding this constructor to Tuples won’t make much sense!

5 Likes

Tuples are much more low-level, being one of the few parts that are defined in non-Julia code in the src directory. They also have some slightly different behaviours than other types, such as allowing an arbitrary number of arguments, and being covariant,

julia> isa((1,3),Tuple{Real,Real})
true

julia> isa(1=>3,Pair{Real,Real})
false

Pairs on the other hand are just a regular immutable type.

8 Likes

I’m quite new to Julia. I found this thread trying to understand the difference between Pair and Tuple. While some of my question have been answered above, I still have these three:

  1. Why is Dict based on Pair, not Tuple ? (Perhaps covariance is bad for Dict ? if I understand what covariance means from simonbyrne’s post.)

  2. How is Pair used outside Dict contexts?

  3. Is covariance the only fundamental semantic difference?

Questions 2 & 3 boil down to, basically, in what context should I prefer one over the other when both seem to work?

I don’t think that (lack of) covariance motivated the implementation of Dict, Pair is simply convenient with the => syntax. In any case, note that internally Dict does not use Pair, it is just for construction.

Pair is generally used in contexts where you need to store a pair of objects that belong together.

I would mostly use Pair to signify intent, and for dispatch. Eg the Dict(::Pair...) constructor is different from the fallback Dict(itr).

1 Like