In mathematica, it is possible to perform immediate definition of a function where the dependent variable is not explicitly mentioned on the RHS. For example:

f1[xval_] := yval xval;
f2[xval_, yval_] = f1[xval] (*Immediate definition since cant use delayed due to yval*);
f2[10, 20]

One obtains the desired output of 200. However, if I try to do the same in Module, the behavior is quite different:

ff[x1_, y1_] := Module[{x = x1, y = y1, f1, f2, yval},
 f1[xval_] := yval xval;
 f2[xval_, yval_] = f1[xval];
 f2[x1, y1]];
ff[10, 20]

When I try to run this, the output of ff[10,20] is 10 yval$166783 instead of 200. I was wondering if there a way to get the same behavior that one gets without a module in this case? Of course, one solution is to use yval as the dependent variable of f1 i.e. f1[xval,yval] instead of just f1[xval]. However, I have several lines of code before the definition of f2 and adding yval as the dependent variable for each such line will involve too much effort.

  • 1
    $\begingroup$ You can use Block instead of Module. You have to read up on how scoping works in order to understand why. I also suspect that there is a better solution to your problem, but that would be another question that would have to explain what problem you are trying to solve is and where this problem is coming. $\endgroup$ – C. E. Jan 21 '18 at 22:18
  • $\begingroup$ I think this boils down to: 20766. $\endgroup$ – Kuba Jan 21 '18 at 22:41

Browse other questions tagged or ask your own question.