# Module with “local functions”

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 { ... }.

-
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 Feb 27 '13 at 16:53
Yes, or just press Ctrl+K –  Ajasja Feb 27 '13 at 17:01
Mathematica 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. Feb 27 '13 at 17:10

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]]
];

-
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 Sep 18 '13 at 17:04
@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 Sep 18 '13 at 18:09
If you truly understand a concept you can always explain it in a simple way---> Now it all makes sense! Thank you Mr. Wizard –  ALEXANDER Sep 18 '13 at 19:59