Tag Info

Hot answers tagged

33

Generally, you want the Trott-Strzebonski in-place evaluation technique: In[47]:= f[x_Real]:=x^2; Hold[{Hold[2.],Hold[3.]}]/.n_Real:>With[{eval = f[n]},eval/;True] Out[48]= Hold[{Hold[4.],Hold[9.]}] It will inject the evaluated r.h.s. into an arbitrarily deep location in the held expression, where the expression was found that matched the rule ...


25

RuleCondition provides an undocumented, but very convenient, way to make replacements in held expressions. For example, if we want to square the odd integers in a held list: In[3]:= Hold[{1, 2, 3, 4, 5}] /. n_Integer :> RuleCondition[n^2, OddQ[n]] Out[3]= Hold[{1, 2, 9, 4, 25}] RuleCondition differs Condition in that the replacement expression is ...


18

Here are a couple of alternatives to Trott-Strzebonski in @R.M's answer: Hold[{3,4,5|6}] /. Verbatim[Alternatives][x__] :> RuleCondition@RandomChoice@List@x Hold[{3, 4, 5}] Hold[{3,4,5|6}] /. Verbatim[Alternatives][x__] :> Block[{}, RandomChoice@List@x /; True] Hold[{3, 4, 6}] They operate on the same principle as Trott-Strzebonski ...


18

This is a case where the Trott-Strzebonski in-place evaluation trick is useful. You use With to inject inside your held expression as: (Hold[{3, 4, 5 | 6}] /. (Verbatim@Alternatives)[x__] :> With[{eval = RandomChoice@List@x}, eval /; True]) Out[1]= Hold[{3, 4, 5}] You should definitely read this post by Leonid, that gives you a good insight into ...


16

The way Mathematica works is that when it encounters a function with arguments it will try to evaluate the arguments first before proceeding to evaluate the function. This behavior can be modified by specifying the various HoldAll, HoldFirst, HoldRest, etc. attributes for a given function. So in your example f[x+1] will be immediately replaced by f[6] ...


14

Not to detract from the existing answers (particularly @WReach's suggestion, which was the same solution that came to my mind as I read your question, and which I will use here), but you may find it easier to define your own references rather than using strings. (In fact, I wouldn't necessarily recommend an approach based on building Mathematica expressions ...


12

It is because, in version 9, the implementation of Plot is loaded from a dump file on its first usage, rather than loading when the kernel starts. One can see this by clearing the ReadProtected attribute: ClearAttributes[Plot, ReadProtected] Information[Plot] (* -> Plot := System`Dump`AutoLoad[ Hold[Plot], Hold[syms], Visualization`Proto` ...


12

#1 Trott-Strzebonski in-place evaluation: hf = HoldForm[1 - 1^2/2 + 1^3/3 - 1^4/4 + 1^5/5 - 1^6/6] hf /. x_Times :> With[{eval = x}, eval /; True] 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 Replace[hf, x_ :> With[{eval = x}, eval /; True], {2}] 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 One may simplify this method using the undocumented function ...


12

The Hold functions enable Mathematica's version of what some other languages call "macros." You can use them for a lot of things, but the essential point is that they preserve the structure of the input. The built-in functions are full of examples: x = 7; Plot[x^2, {x, -2, 2}] Type this in and you'll see that Plot draws the parabola even though "x" was ...


12

While I can't follow your code, I guess your problem is caused by the fact that you get evaluation in between individual replacements, and the fact that Listable functions of several arguments (which includes operators like + and *) have quite peculiar behaviour. The fact that you get a matrix instead of a vector, as well as the fact that you can avoid it ...


11

You are missing Unevaluated: SetAttributes[f, HoldFirst] f[x_] := {SymbolName[Unevaluated@x], x} because SymbolName does not hold its arguments, so you have to prevent evaluation also there. Generally, if you are passing some argument via a chain of function calls, and want to keep it unevaluated, you have to prevent it's evaluation at each stage ...


10

I think that in general, for tasks like this one, tricks like Trott-Strzebonski technique are not the best way, and one really needs expression parsers, which are may be not shorter, but more readable and more extensible. Here is a possible one for your problem: ClearAll[convert]; SetAttributes[convert, {HoldAll}]; convert[x_List] := Map[convert, ...


10

One way to achieve this is to use a "vanishing" wrapper. The idea is to temporarily wrap the substituted expression with a holding symbolic head, and then remove that head in a second replacement: Module[{h} , SetAttributes[h, HoldAll] ; y /. bar[j_] :> RuleCondition[Extract[x, {j}, h]] /. h[x_] :> x ] (* Hold[foo[2+2]] *) Module is used to ensure ...


9

This is possible in the interactive session with $PreRead. I will adopt my solution to the same problem posted in this Mathgroup thread. To quote my explanation from there, the essence of the present solution is to delay the parsing of the code (body) that must be executed inside a given context until run-time, that is, replace code ...


8

I think there is a case to be made for not using List at all. It seems to me that it is a needless complication. Why not instead use Hold in place of List? a = Hold[2 + 2]; b = Hold[4 + 4]; c = Join[a, b] Append[c, Unevaluated[6 + 6]] Hold[2 + 2, 4 + 4] Hold[2 + 2, 4 + 4, 6 + 6] Also: x = Hold @@ {a, b} Length[x] Dimensions[x] Hold[Hold[2 + ...


8

I think your original method is fine, but perhaps this will be more to your liking: Table[With[{n = ni}, Plot[ρ[n, x], {x, 0, L}, PlotLabel -> Defer@ρ[n, x]] ], {ni, 1, 4}] Another, perhaps less fundamental way is Table[ Plot[ρ[n, x], {x, 0, L}, PlotLegends -> Placed["Expressions", Top]] ,{n, 1, 4}]


7

Note that the following works, but generates warning messages. f[y_, a_] := NIntegrate[y^2 + x, {x, 0, a}]; Plot[Table[f[y, a], {a, 1, 3}], {y, 0, 3}, Evaluated -> True] The issue is that Plot (which usually holds it's first argument until specific values of $x$ are plugged in) tries to evaluate the first argument symbolically (due to the Evaluated ...


7

You could do something like InputField[Dynamic[d, (d = HoldForm @@ #) &], Hold[Expression]] This will wrap the expression typed into the input field in HoldForm.


7

Here is yet another possibility (which, in a way, combines some of the suggestions given already): define a new scoping construct, most similar to Function, to perform the task you need: ClearAll[strFunction]; SetAttributes[strFunction, HoldAll]; SyntaxInformation[strFunction] = {"ArgumentsPattern" -> {_, _}, "LocalVariables" -> {"Solve", {1, ...


7

Injector pattern: list = {1, 2, 3}; MakeExpression["list"] /. _[sym_] :> AppendTo[sym, 4] Function (here using the Null syntax trick): Function[, AppendTo[#, 4], HoldAll] @@ MakeExpression["list"]


6

This works: ReleaseHold@Block[{list},Hold[AppendTo["list",1]]/."list"->Symbol["list"]] The mechanism is as follows: The block temporarily undefines list so that after Symbol["list"] is evaluated, evaluation stops. However, the AppendTo shall not be evaluated as long as list is undefined, therefore it is wrapped in Hold. Symbol shall be evaluated, ...


6

One easy way, which does not work for lists of different length, is a = Hold[{2 + 2}]; b = Hold[{4 + 4}]; Thread[{a, b} /. Hold[{a___}] :> Hold[a], Hold] What happens here is the following: first, you can use {a, b} /. Hold[{a___}] :> Hold[a] to get rid of the inner list braces without evaluating your expressions. Since we use {a,b} we will ...


6

As Leonid has explained the problem is that the symbols are created and get their context at parse time, so if you need to avoid generating them in the current (usually "Global`") context, using $PreRead as he explained is the only possibility. If you don't care that the symbols you use are created in the current context AND the context you want to evaluate ...


5

Since you said you wanted text input containing subscripts, superscripts, etc, it sounds like you just want Mathematica's box language: InputField[Dynamic[d], Boxes] Now d is boxes, such as In[39]:= FullForm[d] Out[39]//FullForm=SuperscriptBox["a","b"] You can convert them to expressions with MakeExpression or ToExpression, or interpret them any ...


5

The implementation of your function polynomial can be made simpler. But for your question, The problem (as I said in the little comment above) is in evaluation of your "a" to the Symbol a which is global and has value. Better to use a method like shown by Bill above and other ways to avoid these sorts of things in first place. You can see the problem ...


5

Introduction Questions like this one often suggests that it is not clear how Mathematica works and that it always tries to evaluate expressions. Assume the following simple example a = 1; a + a a*x + 1 In the first line I set a to 1 and in the other two I write down an expression. Now I want that in a+a the result is 2 like one would expect, but in the ...


5

To save and restore data, you could use a Button for saving and an ActionMenu for restoring. The defaultParameters could just be the data -- you have to remember what order you put things, but usually that is important only in two or three places (the Button, the ActionMenu, and your case initializing defaultParameters). Merely for demonstration purposes I ...


5

This is only a hack, but maybe it just gives you short way out of this. Lately, we had a similar discussion in chat about NValues where the problem was related. It this cases Rojo wanted to use NValues to prevent some of the arguments to stay untouched by N. There too, the problem was when N was called from very outside and dived into the subexpressions ...


5

Indeed, Nest and NestList do not support functions with Hold attributes (as well as Fold and FoldList, etc). There were discussions of this in the past. I was able to find one such. As far as I can tell, this is by design. What happens is that NestList (for example) maintains an internal list of intermediate results, the last of which is used in the next ...


5

You can "inject" your variables into the module like this: ClearAll[x, y, z, a, b, c, Foo]; x = 7; SetAttributes[Foo, HoldAll]; Foo[vars_] := Hold[vars] /. _@{v__} :> Module[{v, a, b, c}, x = 43] Foo[{x, y, z}] (* 43 *) x (* 7 *) For more information have a look at some of the questions and answers in these search results: ...



Only top voted, non community-wiki answers of a minimum length are eligible