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, at a high level the code looks something like this:
function solver()
# Start by assigning a bunch of variables, preprocessing, etc.
...
# Choose and execute solve
if alg==1 doAlgorithm1()
elseif alg==2 doAlgorithm2()
elseif alg==3 doAlgorithm3()
end
# Postprocess and return
...
end
Previously when I quickly prototypes I put the solver algorithms right in the code. However, as I am tagging on more and more algorithms this is becoming messy (especially when some are hundreds of lines of code) and so I want to put those calls as a separate function. However, I want them to essentially be the same thing as putting the block of code there: access the same scope, have side effects, etc.
I thought about using a macro for this, but since they eval at the global scope it seemed like the wrong solution. Nested functions seem like they might be doable but I have to define them at the top of the solver (and my intention was to not do that to keep the high level algorithm readable) and there are issues with scoping a nested function within a nested function (for parts which repeat in only some of the algorithms!). I could just define this as another function without trying to keep the same scope but then it would be ugly with a long trail parameters (with each algorithm having the same parameters!)
What is a good way to organize this kind of code? Is there a more Julian approach to this problem?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With