the scenario likes this:
There is an algorithm called alg1, and another algorithm called alg2.
And there is an entry function called solve, how can I pass alg1 to solve then I can use alg1 to compute, and pass alg2 to compute with alg2?
solve(a, b, alg1) #return the results computed with alg1
solve(a, b, alg2) #return the results computed with alg2
Do I need to write the algorithms as functions?
A typical elegant API could be based on the multiple dispatch mechanism and could look like this:
abstract type AbstractAlgo end
struct Algo1 <: AbstractAlgo end
struct Algo2 <: AbstractAlgo
param::Int
end
function solve(a,b,alg::T) where T<:AbstractAlgo
throw("Algorithm $T is not yet implemented")
end
function solve(a,b,alg::Algo1)
println("solving...")
end
Some tests:
julia> solve(1,2,Algo1())
solving...
julia> solve(1,2,Algo2(777))
ERROR: "Algorithm Algo2 is not yet implemented"
In julia you can pass funcions as parameters, so:
function alg1(a,b)
...
end
solve(a,b,alg) = alg(a,b)
# calling solve
answer = solve(a,b,alg1)
Of course there are other ways, as transforming algs is structures and employing multiple dispatch, but the solution above should answer the question..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With