2
$\begingroup$

I would like to define a function within a function to serve as an auxiliary function. In essence, something like this:

f[x_,y_]:=Module[{g[z_]:=2z},x+g[y]]

Where both f and g are in reality complicated functions. But this does not work because Module, or With, do not accept rule delayed in their definitions.

f[1,2]
Module::lvset: Local variable specification {g[z_]:=2 z} contains g[z_]:=2 z, which is an assignment to g[z_]; only assignments to symbols are allowed.

Is there a way around it?

$\endgroup$
2
  • 1
    $\begingroup$ Check the second example in documentation for Module... $\endgroup$
    – Kuba
    Jun 8, 2017 at 9:43
  • $\begingroup$ Indeed, I missed it. $\endgroup$
    – Whelp
    Jun 8, 2017 at 9:47

1 Answer 1

4
$\begingroup$

If you want, you can use

f[x_, y_] := Module[{g}, g[z_] := 2 z; x + g[y]]
$\endgroup$
1
  • $\begingroup$ How to increase reputation fast: answer the easy questions before they get marked as duplicates :p $\endgroup$
    – Kiro
    Jun 8, 2017 at 11:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.