1
$\begingroup$

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!

$\endgroup$
  • $\begingroup$ Sorry, that was a typo. It is corrected in the above version. $\endgroup$ – Nils May 4 at 6:56
  • 4
    $\begingroup$ remove ; after {k->a1}? $\endgroup$ – kglr May 4 at 6:59
  • $\begingroup$ Take a look at this function in the function repository: resources.wolframcloud.com/FunctionRepository/resources/… $\endgroup$ – Sjoerd Smit May 4 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 May 4 at 10:48
1
$\begingroup$

Rules are applied within Module. For example:

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

And then

func[1]
(* 3 *)

func[2]
(* 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

func2[1]
(* 3 *)

func2[2]
(* 7 *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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