Module with "local functions"

26

9

I am trying to use a Module having "local functions", i.e., those which I need to define only inside this module.

So I tried this:

norm[p_] := Module[{
  fun1[p_] := p^2 + p - 1;
  fun2[p_] := p^3 - p^2 + p + 1
 },
 Max[fun1[p], fun2[p]]
];

The function is compiling, but when I try to evaluate it--say, I try:

norm[2]

Its giving me an error telling:

Module::lvsym: Local variable specification {fun1[p_]:=p^2+p-1;fun2[p_]:=p^3-p^2+p+1} contains fun1[p_]:=p^2+p-1;fun2[p_]:=p^3-p^2+p+1, which is not a symbol or an assignment to a symbol

How do we avoid this error? I want to give functions in the space between { ... }.

Pavithran Iyer

Posted 2013-02-27T16:49:59.707

Reputation: 871

That's some determined code formatting. :^) There is a much easier way: just select the entire block of code and click the { } button above the edit box to indent your code as a code block. Also see editing help.

– Mr.Wizard – 2013-02-27T16:53:04.877

2Yes, or just press Ctrl+K – Ajasja – 2013-02-27T17:01:33.483

4Mathematica is not a compiled language. The absence of messages at any particular point is not a good indication of correctness, since the evaluator assumes that what you're doing is meaningful until it arrives at something that's manifestly not. – Oleksandr R. – 2013-02-27T17:10:54.773

Answers

35

You cannot make definitions with patterns on the left-hand side in the first argument of a scoping construct (such as Module). You need do that in the body of the Module. You should also use a different symbol for the internal function parameter.

norm[x_] :=
  Module[{fun1, fun2},
    fun1[p_] := p^2 + p - 1;
    fun2[p_] := p^3 - p^2 + p + 1;
    Max[fun1[x], fun2[x]]
  ];

Closely related:

Mr.Wizard

Posted 2013-02-27T16:49:59.707

Reputation: 259 163

Mr.Wizard I am struggling with understanding module, because in some examples ive see they assign only lists where you have assigned {fun1,fun2}, an other times its functions as you have done above? what is actually happening. I have read the mathematica guide but when i see all the different examples i get confused. – ALEXANDER – 2013-09-18T17:04:08.287

@ALEXANDER You should read answers to (559). I particularly like WReach's answer as a place to start. In my own brief words Module creates local equivalents for the Symbols given in the first argument (fun1 and fun2) above and silently uses these in place of the global versions. For example you may have fun1$325 used in place of fun1 wherever fun1 appears in the body of the module. They can be used for both direct assignments (fun1 = 5) and pattern definitions (as above).

– Mr.Wizard – 2013-09-18T18:09:41.050

1If you truly understand a concept you can always explain it in a simple way---> Now it all makes sense! Thank you Mr. Wizard – ALEXANDER – 2013-09-18T19:59:40.470