1
votes

Just wanted to check if it safe to do the following:

Lets say I have a function 'f(x)' that also depends on other parameters. For example, the function a*Exp[ (x-x0)^2/(2*std^2)]

From the UI I read the user input values (via sliders) for the parameters a and x0 and std, then I make a pure function variable

 f=Function[{x,a,x0,std}, a*Exp[ (x-x0)^2/(2*std^2)]

The above is done in the same context (in the Manipulate control area), when I am reading the user input, then when the user hits a button to run the program, I call another lower level function to process this input, like this

 foo[f,a,x0,std]

then inside foo, it evaluates f over some grid points (x1,x2,etc...) by making calls like this

 foo[f_,a_,x0,std_]:=Module[{x1,x2...},     
   .....
   f[x1,a,x0,std];
   f[x2,a,x0,std];
   f[x3,a,x0,std]; etc... 
   ....
   ]

Notice that inside foo, only the x parameter to the pure function is used, the rest are just coming along for the ride.

But since they are not used inside foo, I am thinking of not passing all the other parameters a,x0,std.

So, I changed the pure function to become

 f=Function[{x}, a*Exp[ (x-x0)^2/(2*std^2)];

then called foo like this

 foo[f]

then inside foo, I do

 foo[f_]:=Module[{},     
   .....
   f[x1];
   f[x2];
   f[x3]; etc...
   ....
   ]

I tested this, and it works. (at first I thought since the context is different inside Module foo, I had to pass a,x0,std along with f. But I did not have to. It seems the a, x0 and stdx values inside the pure function as saved as globals and passed in the pure function body.

My question: do you see any problem with the second approach above? something I am overlooking? in the tests I've done, it works fine so far. And it would make it much simpler, since now I only need to pass the pure function itself, and not pass all the other parameters used to build up, since they are not needed inside foo.

In other words, I am trying to decide between these 2 setups:

enter image description here

Just thought to check.

thanks

1

1 Answers

7
votes

How about something along these lines:

mkf[a_, x0_, std_] := 
 Function[{x}, Evaluate[a*Exp[(x - x0)^2/(2*std^2)]]]

foo[f_] := Module[{x},
      x = 1;
      f[x]
      ]

foo[mkf[1, 1, 1]]

You generate the function you want to use before passing it onwards.