如何在函数中选择算法

ERI*_*QQY 2 algorithm julia

场景是这样的:

有一种算法称为alg1,另一种算法称为alg2

还有一个名为 的入口函数solve,如何传递alg1求解然后我可以使用alg1进行计算,并传递alg2来使用alg2进行计算?

solve(a, b, alg1) #return the results computed with alg1
solve(a, b, alg2) #return the results computed with alg2
Run Code Online (Sandbox Code Playgroud)

我需要将算法编写为函数吗?

Prz*_*fel 7

典型的优雅 API 可以基于多重调度机制,如下所示:

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 
Run Code Online (Sandbox Code Playgroud)

一些测试:

julia> solve(1,2,Algo1())
solving...

julia> solve(1,2,Algo2(777))
ERROR: "Algorithm Algo2 is not yet implemented"
Run Code Online (Sandbox Code Playgroud)