Why wouldn't use tuples for computation?

I was reading this Github page, and came across a post from StefanKarpinski, and he says:

…but you really mostly shouldn’t be doing much computation with tuples in the first place,…

I was wondering if someone could elaborate on why? Is it because tuples are immutable and you may need to construct a new tuple every time a value needs to be updated?

I think because they are not meant for it. If you want to do computations you should use StaticArrays.jl, which wraps tuples.

6 Likes

Notice that that comment is almost eight years old. At the time tuples had very different performance characteristics, predating the classic PR Tuples made me sad (so I fixed them) by Keno · Pull Request #4042 · JuliaLang/julia · GitHub, and dot broadcasting had not been invented.

6 Likes

You may be interested in https://github.com/JuliaArrays/StaticArrays.jl . SArray provides an array-like interface around data stored in a tuple.

https://github.com/JuliaArrays/StaticArrays.jl/blob/master/src/SArray.jl#L18-L30

The is mainly practical for small arrays.

One would have to implement all mathematically sensible computations for tuples. For example, this is not implemented:

julia> x = (1,2)
(1, 2)

julia> 2*x
ERROR: MethodError: no method matching *(::Int64, ::Tuple{Int64,Int64})

The solution to such implementation exists and is the StaticArrays package that everyone is mentioning. StaticArrays are the tuples for which the computations can be performed:

julia> using StaticArrays

julia> x = SVector{2,Float64}(1,2)
2-element SArray{Tuple{2},Float64,1,2} with indices SOneTo(2):
 1.0
 2.0

julia> 2*x
2-element SArray{Tuple{2},Float64,1,2} with indices SOneTo(2):
 2.0
 4.0


2 Likes

Dot broadcasting works just fine with plain tuples.

julia> 2 .* (1, 2)
(2, 4)

It’s extremely convenient for e.g. size computations.

1 Like

Sure, but multiplication by a scalar does not, summing tuples does not, multiplication by a matrix does not etc. Probably if it was chosen to put tuples as center type for computations those should have been implemented as well.