I’m working on Markov Chains where a lot of recursive functions have a mathematical parametric equation with a base case, simplified to
function f(xs, 1)
@info "Base case"
end
function f(xs, val)
@info "General case val > 1"
end
To my knowledge, I can’t specialize on value , only on type. I want to avoid this
function f(xs, x)
if x <= 1
@info "handle base case"
end
@info "handle generic case"
end
While the above seems trivial, in practice the actual functions quickly become combinatoric with multiple parameter base cases, ranges, etc.
What I tried:
- I can define an enum with the base case values
@enum basecase B=1
function f(xs, x::basecase)
@info "basecase"
end
function f(xs, x) # Generic
@info "Not base"
end
I think I can do @specialize
with ranges, e.g. 1:1 would be the base case range, and 2:? would be the general case.
My key objective is to keep the code as clean and elegant as possible, and a close as possible to the mathematical function specifications, while leveraging the type system for safety (and performance).
For example, the enum example fails because f(1, 1)
will not call the Enum specialization, and f(1, 0)
is invalid, but not caught.
This is related to C++'s constant value type specialization
C++ Template Specialization with Constant Value - Stack Overflow
Any help/pointers/suggestions are much appreciated.
This is related to keyword specialization, and from reading I believe Julia already specializes in the background, but this would not allow me (I think?) to define function types by their default values (the base case)?