I have a working code like the following:
function test(a,b)
c = a + b
d = a - b
e = c + 2 * d
end
but I now want to sometimes make b
a constant s.t.
const b = 1.5
function test(a)
c = a + b
d = a - b
e = c + 2 * d
end
My experience with C makes me want to do something like
#ifdef USECONST
const b = 1.5
function test(a)
#else
function test(a,b)
#endif
c = a + b
d = a - b
e = c + 2 * d
end
Is there a Julia syntax that can do this? I’m basically looking for an easy way for me to reuse the function body (c=…, d=…, e=…) while still have the option of using b as either a constant or an input parameter in different applications. Thanks!
function test(a,b = 1.5)
c = a + b
d = a - b
e = c + 2 * d
end
I believe that is what you want. With this you can call test(3.3)
or call test(3.3, 1.25)
. If b
isn’t provided then it’s value will be 1.5.
Wow thank you for your instant answer! Unfortunately, in my case, b is loaded from a file and is in fact a large array that I cannot hard-code it…
Then I don’t see the advantage of just defining test(a, b)
, and calling it with a b
you either define in the source or load from a file.
Maybe a closure?
function maketest(defaultB)
return a -> begin
c = a + defaultB
d = a - defaultB
e = c + 2*d
end
end
test = maketest(1.5)
I realize I’m not giving the full picture. I’m trying to embed my Julia code from C calling the function test(a,b)
. However, b is a struct containing several large arrays, and I don’t know how to do embedding with that. Fortunately, b is unchanged through the entire calculation of test
so my solution is to write b into a file, or files as I have three different sets of b’s as options and load it back when start-up (when I do using MyModule
). The original function test(a,b) is still useful when I’m in pure Julia mode and want to switch between different sets of b’s or explore a new b.
I just realized that the default value of b doesn’t have to be hard-coded! The following code fits my need
struct Par{T}
x::T
y::T
z::T
end
b_global = Par{Float64}(1,1,1)
function test(a, b=b_global)
@show b
#some code
end
test(1)
test(1,Par{Float64}(0,0,0))
Thanks everyone!