1

I am wondering about types in Julia, more specific Union. For instance, I have made a function where I add the length of my input a into a vector len_a. If a is of type VariableRefI want the length to be 1. I write it like this;

function add_length!(a::VariableRef,lenComp::Vector, i::Int)

    len_a[i] = 1.0; 
end

However, if a is not of type VariableRef I want it to take the length. So I am wondering if I should do as I have done below, like defining a new type by using Union:

NotVariableRef = Union{Vector, NonlinearExpression, QuadExpr, AffExpr}

function add_length!(a::NotVariableRef,len_a::Vector, i::Int) 

    len_a[i] = length(a)
end

or if I should do it like this;

function add_length!(a::Any,len_a::Vector, i::Int) 

    len_a[i] = length(a)
end

What is the "right" way of doing it? And is this: len_a::Vector, i::Int) alright or should I have something like len_a::Vector{Int}, i::Int64). I am a bit confused by this type system.

Annaquest
  • 131
  • 6
  • 1
    If you are storing lengths inside `len_a`, then presumably you would write `len_a[i] = 1`, not `len_a[i] = 1.0`, since lengths are integers, not floats. – DNF Feb 22 '23 at 11:48

1 Answers1

2

Julia is using multiple dispatch to select a particular method to be executed.

For multiple dispatch among available methods Julia will use the one with the most concrete type. Hence there is no need to define something like NotVariableRef. Normally you would do:

function add_length!(len_a, a::VariableRef, i)
    len_a[i] = 1.0
end
function add_length!(len_a, a, i)
    len_a[i] = length(a)
end

With this code the appropriate method will be chosen depending on the type of a. Note that by Julia convention I moved the len_a parameter to the front as this is the one being mutated (usually ...! functions mutate the first parameter). I also removed the types as they are not necessary. However if you need I would rather use abstract types for parameters of your function such as AbstractVector and Integer to have a greater API flexibility.

Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62
  • Thank you so much! However, I thought `i::int` etc. would help with the speed or make the code "safer". That is not the case or? – Annaquest Feb 22 '23 at 10:14
  • 1
    No, the type only matters for performance when you define data structures (`struct`) or data containers with parametric types (eg. `Vector`). In case of function parameters types are efficiently handled by Julia compiler. Avoiding writing overly-specific types is also recommended in Julia Style Guide https://docs.julialang.org/en/v1/manual/style-guide/ . For a detailed discussion on performance and types for containers see https://docs.julialang.org/en/v1/manual/performance-tips/. – Przemyslaw Szufel Feb 22 '23 at 10:25