I am a fairly new user of Julia so may have misconceptions about the language’s capabilities and behaviour.
Problem Statement
I have implemented the most general form of an algorithm I am interested in, which is parameterised by multiple vectors and matrices. Although this general form is sometimes used, most of the time I will only be interested in the cases where some of the vectors/matrices are zero, or the matrices are the identity/multiples of the identity.
As a minimal example, let’s consider the function
function linear_transformation(x::Vector{Float64}, A::Matrix{Float64}, b::Vector{Float64})
return A * x + b
end
I would like to have automatically generated, optimised versions of this function for the cases:
- A is zero
- A is the identity
- b is zero
E.g. for the first case, I would ideally like the code to run as quickly as simply returning b
.
It’s also worth noting that such optimisations will likely have ripple effects—one matrix being zero might cause another to be zero, and so on.
I appreciate that this is a lot to ask for (especially for a non-symbolic, eagerly executed language) so I’m not expecting a perfect solution to this. Instead, I would love to have an open discussion about this topic and hopefully find some ways I can get closer to my desired outcome.
Initial Thoughts
A manual way of approaching this would be to write variants of linear_transformation
dispatching on zero values. Obviously, this is not a scalable solution, but I am also under the impression that value dispatch is discouraged in Julia and leads to inefficient code.
The UniformScaling
matrix seems related to what I’m asking for, though I’m not completely sure it does exactly what I’m after. Perhaps, creating similar Identity
and Zero
matrices inspired by this is a good approach.
Can macros be used to achieve this task?