Hi,
so I’m trying to do define functions as fields of a mutable struct based on input parameters. The general structure of which has the following form
module TestModule
mutable struct TestStruct
F
function TestStruct(args...)
f(x) = x;
if length(args)==0
println("0 args")
f(x) = x
println("The value of f(x)=x at x=1.0 is $(f(1.0))")
return new(f)
elseif length(args)>0
println("at least 1 arg")
f(x) = -x;
println("The value of f(x)=-x at x=1.0 is $(f(1.0))")
return new(f)
end
end
end
end
which seems to produce the wrong value for f(x), in the sense that
c=MyModule.MyStruct();
produces
0 args
The value of f(x)=x at x=1.0 is -1.0
which is wrong, and, e.g.
c=MyModule.MyStruct(1);
gives
at least 1 arg
The value of f(x)=-x at x=1.0 is -1.0
However, if I remove all occurrences of elseif , I get a correct assignment of c.F function to f(x) = x, i.e.
module TestModule
mutable struct TestStruct
F
function TestStruct(args...)
f(x) = x;
if length(args)==0
println("0 args")
f(x) = x
println("The value of f(x)=x at x=1.0 is $(f(1.0))")
return new(f)
end
end
end
end
Is this behavior intentional? am I’m doing weird design flops?
how do I get the field F of a mutable struct to be assigned the correct function in the ifelse environment?
Thanks!