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$
4
  • $\begingroup$ Sorry, that was a typo. It is corrected in the above version. $\endgroup$ Commented May 4, 2019 at 6:56
  • 4
    $\begingroup$ remove ; after {k->a1}? $\endgroup$ 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$ Commented May 4, 2019 at 10:48

1 Answer 1

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 and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.