I am trying to create a function that would allow for changing a formula and coefficients in Julia. I am 80% sure I should be using anonymous functions for this?
This SO post using python is a more discrete example of what I am trying to accomplish (in particular the base python example by chepner, rather than using a library). Pass a formula as a function parameter in python
I also found this SO post using Julia that uses a type to store needed parameters and then pass them to a function. How to pass parameter list to a function in Julia
Using these as a base, this is what I have created so far:
#Create composite type
type Params
formula
b1::Float64
b2::Float64
end
#create instance of type and load
foo=Params((b1,b2,X)-> X^b1+X+b2,0.004,0.005)
#create function
function DoMath(X,p::Params)
p.formula(X,varargs...) #??
end
Am I on the right track as to how to structure this by using composite types and/or lambdas? I don't have any CS training and I am muddling my way through many concepts while trying to learn Julia.
What is the correct syntax for a function that can allow a user to change the formula and any coeffs. for a given X? Ultimately, I am imagining something with functionality like:
DoMath(4) #some default formula with changing X DoMath(4, X*b1 +X*b2) #change X and change formula DoMath(4, (X,b1,b2,b3)->X*b1+X*b2+x*b3) # change x, change formula to a 3 parameter function
Thank you
Update: I got it working by following @Chris's syntax. One thing I had to tinker with is using
(p::Params)(x) = p.formula(x,p.b) #p.b, not just b otherwise error
and I had to wrap the 2.0 and 3.0 in an array before calling
p = Params((x,b)->x*b[1]+b[2],[2.0,3.0])