Reputation: 683
I want to make a function that create a new variable, my goal is:
struct Test
setArg(varName,Float64,10.1,1.2)
end
That should return a struct Test
with one argument varName
from the Type Float64
with max 10.1
and min 1.2
.
My problem is to know how to make the that function return a variable.
Or I'm thinking in another approach like this:
struct Test
varName::setArg(Float64,10.1,1.2)
end
here the function should just define a Type and max and min for the argument and that is okay, but I will prefer the first one if it is possible to do it in Julia.
So the question is how should my function/Type setArg
look like?
Upvotes: 0
Views: 74
Reputation: 1313
You could create an incomplete mutable struct:
struct MyTest{T} #to allow different types while maintaining performance
min::T
max::T
val::T
valueset::Bool #to check if the struct is initialized
sym::Symbol #to access
end
to allow the user to access the value with the identifier provided, we overload Base.getproperty
for the MyTest
struct:
function Base.getproperty(val::MyStruct, sym::Symbol)
#identifier matches and the value was set
if val.sym==sym & val.valueset
return val.val
else
throw(error("oops")
end
end
finally, we make the struct with setArg:
function setArg(sym, type, min, max)
min = convert(type, min)
max = convert(type, max)
dummyval = zero(type) #
return MyTest(min, max, dummyval, false, sym)
end
finally, we make a function that sets the value, by calling the struct:
function (val::MyTest)(value) #a functor
if val.min <= value <= val.max
val.val = value
val.valueset = true
else
throw(error("out of bounds"))
end
return val
end
I imagine that the usecase is something like this :
constructor = setArg(:myname, Float64, 0.2, 0.5)
val1 = constructor(0.4)
val2 = constructor(0.5)
val3 = constructor(0.6) #error
val2.myname == 0.5
Upvotes: 1