How can we define a function that works like f[x_]=ComputeSomething[x] and treats x as a variable that does not have a value? We could call this function LocalSet and the computation should be done when the assignment is made as in the following example.
var=3;
LocalSet[f[var_],Normal[Series[Exp[var],{var,0,3}]]];
DownValues[f]
(*
---> {HoldPattern[f[var_]]:>1+var+var^2/2+var^3/6}
*)
var
(*
---> 3
*)
Notice I don't want to be limited to a pattern variable (x_). The function called LocalSet should figure out what symbols are used for patterns and evalute the right side with those variables in a Block construct.
f[x_?NumericQ] := (Print["numeric"]; x); n = 5; localSet[g[n_], f[n]], which has different behaviour when the semicolon is omitted. I think it's important here that the expression not be evaluated withnhaving a value---there's no telling what that might lead to. – Szabolcs Feb 19 '12 at 12:12Heads->Trueoption inCases, if you want to coverSubValues. Right now an attempt to assign to sayf[var_][1]will produce an error. If you want to be totally safe, I'd also useHoldCompletein place ofHold. – Leonid Shifrin Feb 19 '12 at 13:54Heads -> True. RegardingHoldCompleteI hesitate to use it unless I know it is needed because there are times it is not wanted. If you have a different opinion you know I would like to hear it. – Mr.Wizard Feb 19 '12 at 14:04ClearAll[var];var /: _[var] := var; var = 3;The current version oflocalSetwon't work then. This is of course a rather contrived example, but if we want to make things robust, any example should work. For this case, I don't see howHoldCompletecan bring any unwanted effects, so I'd use it. – Leonid Shifrin Feb 19 '12 at 14:13HoldAll->HoldAllComplete,Hold->HoldComplete} correct? – Mr.Wizard Feb 19 '12 at 15:43HoldAllmay be enough, so justHold->HoldCompleteI think. – Leonid Shifrin Feb 19 '12 at 20:50localSet[f[...],rhs], because they will be insidef. So, as long aslocalSetisHoldAll, you don't have to care about them, exactly due to the depth-1 limitation forUpValuessearch. But when you destructure, you haveHold[sym], and hereHoldCompleteis essential. – Leonid Shifrin Feb 19 '12 at 20:56Module[{tag},Reap[Unevaluated[lhs]/.{i_Verbatim:>i, Verbatim[Pattern][p_, _]/;Sow[HoldComplete[p], tag]:>Null}, tag][[1, -1]]]– Rojo Jul 19 '13 at 17:24