Julia: Structuring code with many different but related algorithm choices

前端 未结 3 1606
旧巷少年郎
旧巷少年郎 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:19

    Since julia functions can modify their arguments, side effects can usually be handled by making whatever you want to modify one of the arguments of the function.

    This demo uses anonymous functions to allow your solvers to take different parameters, if you want. I'm not sure it's exactly what you're asking, but if you don't know about this already it might be informative.

    using Base.Test
    
    function solver1(data, initialize::Bool)
        if initialize
            fill!(data, 0)
        end
        return 1
    end
    function solver2(data, hellostring)
        println(hellostring)
        return 2
    end
    
    function solver(f)
        data = [1,2,3,4]
        ret = f(data)
        println(sum(data))
        return ret
    end
    
    @test solver(data->solver1(data, false)) == 1
    @test solver(data->solver1(data, true)) == 1
    @test solver(data->solver2(data, "hello, world")) == 2
    

    which generates the output

    10
    0
    hello, world
    10
    

提交回复
热议问题