首页 > 解决方案 > 如何在函数中选择算法

问题描述

场景是这样的:

有一种算法称为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

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

标签: algorithmjulia

解决方案


一个典型的优雅 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 

一些测试:

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

julia> solve(1,2,Algo2(777))
ERROR: "Algorithm Algo2 is not yet implemented"

推荐阅读