tst
tst

Reputation: 1172

Julia: How to define correctly a function that uses types that depend on numbers?

I use arrays but I do not need to change the length at any point, but at the same time I do not know their length while I am writing the code. I know the length only when I need to create them.

In particular I am using StaticArrays and I want to define a function of the type f(v::MVector{N,Float64}) that will accept as input an MVector of any length. How do I type this in?

Upvotes: 3

Views: 134

Answers (1)

Dan Getz
Dan Getz

Reputation: 18217

For a running example, suppose we have a vector mv which is fixed length, but we know its length only at run-time. It could be defined like so:

julia> using StaticArrays

julia> mv = @MVector rand(4)
4-element MVector{4,Float64}:
 0.978253
 0.691035
 0.988942
 0.770601

To define a function which operates on this vector, we could write:

julia> mysum(v::MVector{N,Float64}) where {N} = sum(v)

Note the where {N} notation which makes it address all fixed sizes.

But this is unnecessary. Writing:

julia> mysum2(v) = sum(v)

works to optimize for the specific length, even at run-time, since a new version of the function is compiled for each type of the parameter. This is because Julia specializes a function according to parameter types. MVectors include the length in their type, and so a specialized function for this length is generated at run-time and used.

Upvotes: 7

Related Questions