Julia: Structuring code with many different but related algorithm choices

前端 未结 3 1635
旧巷少年郎
旧巷少年郎 2021-01-20 11:24

I am looking for an elegant way to re-arrange my code. For developing solvers, what happens is you can have a lot of different options which have the same setup. For example

3条回答
  •  既然无缘
    2021-01-20 12:18

    The way to do this is just to pass the solver function as a parameter to the solve function:

    solver1(state) = "Solver 1 with state $state"
    
    function solve(solver)
    
        # set up the state here, e.g. in a State object
    
        state = [1, 2]
    
        result = solver(state)
    
    end
    
    solve(solver1)
    

    "Accessing the same scope" is the same as passing over a variable containing the local state you need. "Having effects" is the same as passing back variables from the solver method.

    If the solver functions are sufficiently simple, they will be inlined by the compiler into the solve function, and it will be as if you had typed them in directly (if you were worried about the overhead of the function call).

    EDIT: Didn't read carefully enough. The "long trail of parameters" you mention you can just store into a special type, e.g.

    type SolverParams
        a::Int
        b::Float64
        params::Vector{Float64}
    end
    

    Then each solver takes an argument of this type. Or it could just be a tuple that you pass into the solver.

提交回复
热议问题