Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I choose algorithms in a function

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?

like image 883
ERIKQQY Avatar asked Jan 21 '26 22:01

ERIKQQY


2 Answers

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"
like image 145
Przemyslaw Szufel Avatar answered Jan 23 '26 16:01

Przemyslaw Szufel


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..

like image 41
Antonello Avatar answered Jan 23 '26 15:01

Antonello