Julia: Structuring code with many different but related algorithm choices

前端 未结 3 1604
旧巷少年郎
旧巷少年郎 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 11:54

    I am not sure if this is a better approach than using a state object, but you can use macros to achieve what you want:

    macro f() 
        quote 
            b = 5
            x = a * b
            x  # the value of a block is equal to its last statement
        end
    end
    
    function foo()
        a = 2
        b = 3
        x = @f()
        x, b  # (10,3)
    end
    

    Note that Julia automatically replaces b and x within the macro with a unique name to avoid side effects. If you want to have side effects, you can use the following:

    macro g() 
        esc(quote 
            b = 5
            x = a * b
        end)
    end
    
    function bar()
        a = 2
        b = 3
        @g()
        x, b  # (10,5)
    end
    

    This is equivalent to replacing @g() with the code between quote and end from the definition of g. One can also define a small convenience macro:

    macro def(name, definition)
        return quote 
            macro $(esc(name))()
                esc($(Expr(:quote, definition)))
            end
        end
    end
    

    With that, g could have been defined as

    @def g begin
        b = 5
        x = a*b
    end
    

提交回复
热议问题