I have a rather long piece of code inside a Module, and I want to provide different parameters to the different pieces inside the Module. Lets call the inside expr, and the parameter(s) I would like to choose a. Then I would try something like this:

func[a_] := Module[{a1 = a},
expr /. {k -> a1};

expr is a rather long analytic expression depending on k, into which I want to plug different values a into. Well, long story short, the above approach doesn't work, as the rule is simply not applied inside the Module. I have also tried different variations of this and used Block, but non worked. Is there a way to make this work, by using rules?

I am fairly new to all this Module and Block business, so some help would be greatly appreciated!

  • $\begingroup$ Sorry, that was a typo. It is corrected in the above version. $\endgroup$
    – Nils
    Commented May 4, 2019 at 6:56
  • 4
    $\begingroup$ remove ; after {k->a1}? $\endgroup$
    – kglr
    Commented May 4, 2019 at 6:59
  • $\begingroup$ Take a look at this function in the function repository: resources.wolframcloud.com/FunctionRepository/resources/… $\endgroup$ Commented May 4, 2019 at 8:17
  • 1
    $\begingroup$ expr /. k->a1 does not modify expr. Instead, it generates a new expression, which you need to assign to a new variable: newexpr = expr /. k->a1. $\endgroup$
    – Roman
    Commented May 4, 2019 at 10:48

1 Answer 1


Rules are applied within Module. For example:

func[a_] := Module[
   a1 = a
  1 + k + k^2 /. k -> a1

And then

(* 3 *)

(* 7 *)

However, the way you have stated the problem there is no need to use Rule at all.

As I understand your question you could simply write:

func2[k_] := 1 + k + k^2

and then

(* 3 *)

(* 7 *)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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