algorithm - 如何在函数中选择算法
问题描述
场景是这样的:
有一种算法称为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
我需要将算法编写为函数吗?
解决方案
一个典型的优雅 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"
推荐阅读
- computer-vision - 这种在pytorch中计算top-5准确率的方法正确吗?
- c# - 如何在 C# 中订阅 snmpclient(打印机)
- python - 无法循环 random.randint 并生成像骰子一样的新数字
- c++ - 是否可以将 QML 项目添加到以 mainwindow.ui 形式创建的窗口中?
- blockchain - 如果连接到 Mumbai RPC 测试网,则无法获取帐户 ID
- java - 如何在 android studio 中的应用程序中使用显示布局边界功能?
- ios - 在制作 xcframework 时加载依赖库时应用程序崩溃
- azure-devops - 查询:Azure Devops 中自托管代理中的文件夹
- mongodb - 根据键查询 mongoDB 映射
- microsoft-graph-sdks - 如何将此 Microsoft 图形代码转换为 php 请求