Re: Conditional SetDelayed with Replacement
- To: mathgroup at smc.vnet.net
- Subject: [mg92808] Re: Conditional SetDelayed with Replacement
- From: Szabolcs Horvat <szhorvat at gmail.com>
- Date: Tue, 14 Oct 2008 04:54:55 -0400 (EDT)
- Organization: University of Bergen
- References: <gcv7d5$e1i$1@smc.vnet.net>
Raffy wrote: > I've been having difficulty getting the following code to work as > desired. > > Clear[f]; > Do[f[x_ /; x < i^2] = i, {i, 5}]; > > The problem should be obvious: the i^2 is not be evaluated (since its > held by SetDelayed). > > The only solution I've found thus far, has been doing the following: > > Clear[f]; > (f[x_ /; x < #^2] = #)& /@ Range[5] > or > Do[(f[x_ /; x < #^2] = #)&[i], {i, 5}]; > > What kind of Hold, ReleaseHold, Evalulate, or Pattern Replacement > would be needed to get the first example working without using a pure- > function for replacement? > With[] can be used to inject values into held expressions: Clear[f] Do[With[{i = j}, f[x_ /; x < i^2] = i], {j, 5}] ReplaceAll works too, but it's somewhat messier: Clear[f] Do[Unevaluated[f[x_ /; x < i^2] = i] /. i -> j, {j, 5}]