Tell me more ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

share|improve this question
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 at 16:53
1  
Yes, or just press Ctrl+K – Ajasja Feb 27 at 17:01
2  
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 at 17:10

1 Answer

up vote 11 down vote accepted

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]]
  ];
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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