0
$\begingroup$

As I understand, an expression like Module[{var},expr[var]] localizes var and evaluates expr[var] with this localized symbol. But the following code behaves as if a pattern created inside the Module were also somehow localized, unlike the variable inside the first part of Module call:

Clear[f, g]
Module[{dsol = DSolve[f''[x] == w^2 f[x], f[x], x]}, 
 g[x_, w_] = f[x] /. First@dsol]

If I replace Module with Block, then, of course, the expression evaluates as expected. But I would still like to make sense of the behavior. So here's the difference between the evaluation in Module and Block:

  1. Module:
Clear[f, g]
Module[{dsol = DSolve[f''[x] == w^2 f[x], f[x], x]},
 Print[dsol // FullForm];
 Print[f[x] // FullForm];
 FullForm@Hold[g[x_, w_] = f[x] /. First@dsol] /. HoldPattern[First@dsol] :> RuleCondition[First@dsol]
]
List[List[Rule[f[x],Plus[Times[Power[E,Times[w,x]],C[1]],Times[Power[E,Times[-1,w,x]],C[2]]]]]]
f[x]
Hold[Set[g[Pattern[x$,Blank[]],Pattern[w$,Blank[]]],
 ReplaceAll[f[x$],List[Rule[f[x],Plus[Times[Power[E,Times[w,x]],C[1]],
                                      Times[Power[E,Times[-1,w,x]],C[2]]]]]]]]
  1. Block:
Clear[f, g]
Block[{dsol = DSolve[f''[x] == w^2 f[x], f[x], x]},
 Print[dsol // FullForm];
 Print[f[x] // FullForm];
 FullForm@Hold[g[x_, w_] = f[x] /. First@dsol] /. HoldPattern[First@dsol] :> RuleCondition[First@dsol]
]
List[List[Rule[f[x],Plus[Times[Power[E,Times[w,x]],C[1]],Times[Power[E,Times[-1,w,x]],C[2]]]]]]
f[x]
Hold[Set[g[Pattern[x,Blank[]],Pattern[w,Blank[]]],
 ReplaceAll[f[x],List[Rule[f[x],Plus[Times[Power[E,Times[w,x]],C[1]],
                                     Times[Power[E,Times[-1,w,x]],C[2]]]]]]]]

Notice how the patterns and placeholders in the former case become x$, w$ while in the latter they don't. So what's happening? Why are these symbols, in addition to dsol, being localized by Module?

$\endgroup$

marked as duplicate by Kuba Jul 27 at 5:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ Linked topic covers it well, let me know if you disagree with closing $\endgroup$ – Kuba Jul 27 at 5:53