153

In Mathematica, all functions are really just patterns, and there are different kinds of those. Let's start with OwnValues, which is the pattern type of a variable as you know it from other programming languages. The symbol having the OwnValue has, as the name suggests, intrinsic, "own", value. In[1] := a = 2; OwnValues[a] Out[1] := {HoldPattern[a] :> ...


121

Preamble In addition to the differences between these global rules reflected in the patterns for which assignment operators put the global rule into one or another ...Value, there is another, and IMO,no less important difference, and that is in how these rules are used in the evaluation sequence. Evaluation: OwnValues The OwnValues represent symbols ...


58

Preamble This is a very good question, because answering it will make it very clear what immutability means, both in general and in the context of Associations. General A few general words on immutability Associations are immutable data structures. This means that they carry no state, and a copy of an Association is another completely independent ...


48

References and intro First, let me point out that = is shorthand for Set and := for SetDelayed; this facilitates searching the docs. Also, as Simon Woods points out in a comment to the question, there is a tutorial on this. Explanation The basic distinction is this: y[x_]=expr means evaluate expr, then whenever you see y[something] evaluate evaluate what ...


45

Your question really is about how to make attributes of f affect also the evaluation of other groups of elements, like y and z in f[x___][y___][z___]. To my knowledge, you can not do it other than using tricks like returning a pure function and the like. This is because, the only tool you have to intercept the stages of evaluation sequence when y and z are ...


37

Some observations on Removed Removed is not a normal head, but rather a print form. Consider a definition x := y Once we Remove the y, we invalidate x in a subtle but permanent way - reintroducing the y into the session won't help. Remove is really a rather special-purpose destructuve operation, aimed more at removing auto-generated symbols. In a system ...


36

Usually you don't want to actually assign values to x and y, and you would use replacement rules instead: sols = Solve[y^2 == 13 x + 17 && y == 193 x + 29, {x, y}]; {x, y} /. sols[[1]] or for the second solution: {x, y} /. sols[[2]] If you really want to assign values to x and y globally, you could use: Set @@@ sols[[1]] but you must clear x ...


33

You can do this : s = Solve[y^2 == 13 x + 17 && y == 193 x + 29, {x, y}]; xx = s[[All, 1, 2]]; yy = s[[All, 2, 2]]; Now you can access solutions, this way xx[[1]], yy[[2]]. If you prefer to collect solutions in Array, there is another way : X = Array[ x, {Length@s}]; Y = Array[ y, {Length@s}]; x[k_] /; MemberQ[ Range[ Length @ s], k] := s[[k, 1, ...


32

I believe Increment (more accurately PreIncrement as george2079 noted) is essentially this: SetAttributes[inc, HoldFirst] inc[a_] := a = (a + 1) This exhibits the same behavior, e.g. f[] := (Print[#]; #) &@RandomInteger[{1, 3}] v = {0, 0, 0}; inc @ v[[f[]]]; 2 1 Here f[] is evaluated twice because parameter a is used twice within Set. On the ...


30

I hesitate to add anything after @Leonid's comprehensive answer, but I'd like to point out that an easy way to achieve the stated goal is to define f like this: f[x_] := <| x, "isFirstValueTrue" -> x@"firstValue" |> ... which yields the desired result when mapped across the associations in x: f /@ x (* { <|"firstValue" -> True, "...


26

This seems to work: a = 1; b = 2; c = 3; d = 4; Scan[Function[p, p = 5, HoldAll], Hold[a, b, c, d]] Now, try evaluating {a, b, c, d}. Here's the version with slots: Scan[Function[Null, # = 5, HoldAll], Hold[a, b, c, d]]


21

How about this: list = {1, 2, 3}; ToExpression["list", InputForm, Hold] /. Hold[v_] :> AppendTo[v, 3] {1, 2, 3, 3} list {1, 2, 3, 3}


21

Unique will do precisely this. Try for example Unique[x], which returns a symbol with a name similar to x$123. Here I should mention the Temporary attribute as well, which, when associated with a symbol, causes that symbol to be removed from the system when it's no longer referenced. This is occasionally useful when you need Unique. But whenever you do ...


21

Yes, at least in one place. x = {1, 2, 3} x[[2]] = 8; All right there, but y := {1, 2, 3} y[[2]] = 8 gives Set::noval: Symbol y in part assignment does not have an immediate value Credit to this old comment by Leonid. Also note the point on memory usage: [...] I'd guess that delayed definitions may use some intermediate internal variables, ...


21

This is a fairly natural question and I feel it is worthy of attention. I am going to answer in two parts. First, I am going to show a method that is more appropriate for Mathematica programming and which I recommend you use instead. Then I will show how to force the action you are attempting. Better Alternatives The common way to accomplish ...


21

You asked for a general explanation instead of just focusing on specific application examples, so here it goes ... The concepts of "pass by reference" and "pass by value" that you may know from languages like C do not apply very well to Mathematica. Do not try to think in this framework. The right question is not "how to pass by reference/value", but how ...


20

Try for example SetAttributes[def, HoldAll] def[s_Symbol, v_] := Function[Null, s[x_] := #, HoldFirst][v] Unnamed functions just don't care :) Other alternatives that should also work (but I would use the previous approach) def[s_Symbol, v_] := Identity[SetDelayed][HoldPattern@s[x_], v]; def[s_Symbol, v_] := Unevaluated[s[x_] := "Hello"] /. "Hello" -> ...


19

This might work as you expect and be save even if definitions for x exist: Block[{x}, f[x_] = D[Sin[x], x];] I would strongly suggest that you get familiar with Derivative and pure functions if you work with symbolic derivatives, though. This will make your life much easier in the long term. Your example would reduce to: f = Derivative[1][Sin] and a more ...


19

Update: Version 10 built-in function Values does value extraction conveniently for rules appearing in lists of arbitrary lengths and depths: {{x1, y1}, {x2, y2}} = Values[Solve[y^2 == 13 x + 17 && y == 193 x + 29, {x, y}]] (* {{(-11181-Sqrt[2242057])/74498,1/386 (13-Sqrt[2242057])}, {(-11181+Sqrt[2242057])/74498,1/386 (13+Sqrt[2242057])}} *) ...


18

We can define a new "variable container" that can be used to assign the same value to multiple variables: ClearAll[vars] SetAttributes[vars, HoldAll] vars /: s:(_vars = _) := CompoundExpression @@ Thread[Unevaluated@s, vars, 1] It is used like this: In[4]:= ClearAll[a, b, c, d] vars[a, b, c, d] = 5 Out[5]= 5 In[6]:= {a, b, c, d} Out[6]= {5, 5, 5, ...


18

General considerations To my mind, the only robust way to do this is to build some custom object model in Mathematica, and in particular to restrict the way values can be changed to some well-defined route you can control. Because, as it follows from one of the discussions you linked to, there seems to be no reliable way to intercept arbitrary value changes ...


17

You can use Unset for this, like so: a[b_, c_] =. =. works with UpValues too (the full form of this has TagUnset): a /: Subscript[a,2] =. You need to use the same pattern in Unset that you used in the definition. Get this using Information (i.e. ?a).


16

Perhaps something like this: SetAttributes[localSet, HoldAll] localSet[lhs_, rhs_] := Union @@ Cases[ Unevaluated[lhs], Verbatim[Pattern][p_, _] :> HoldComplete[p], Infinity, Heads -> True ] /. _[x___] :> Block[{x}, lhs = rhs;] Test: var=3; localSet[f[var_],Normal[Series[Exp[var],{var,0,3}]]] DownValues[f] {HoldPattern[f[...


16

If you insist on working with your list where you assemble variables, this will do it: setValues = Function[{vlist, val}, OwnValues[vlist] /. (_ :> vars_) :> Replace[Unevaluated@vars, var_ :> (var = val), {1}], HoldFirst]; For example: In[73]:= myList:={a,b,c,d} In[74]:= a=1;b=2;c=3;d=4; In[77]:= setValues[myList,5]; In[...


16

You can use Unset or =. to remove a single definition. For example, for your above function its DownValues are DownValues@a Out[1]= {HoldPattern[a[b_]] :> 2, HoldPattern[a[b_, c_]] :> 3} Unsetting the definition for a[b_, c_], a[b_, c_] =. DownValues@a Out[2]= {HoldPattern[a[b_]] :> 2} It works similarly for UpValues too, i.e., you can do a /: ...


16

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 ...


15

The behaviour you observed is completely independent of NumericQ. It could also be seen with a function foo which has the initial definition foo[_]=False. Example 1: Initially you define NumerixQ[x]=True, which tells Mathematica that whenever it evaluates the expression NumericQ[x], it should evaluate to True. Since for symbols, it is pre-defined to return ...


15

The reason is that AppendTo and PrependTo actually replace the whole list with a new one, rather than only changing a single element. In that sense, they are not really "in-place". They are in-place in the sense that the result gets assigned back to the same variable. You can see using Trace, that AppendTo and PrependTo in fact expand: bar[1]={4,3,2,1}; ...


14

TracePrint will show you what happens: PreIncrement takes it's argument x, evaluates it (let's call the result result), then evaluates x = result+1. Note that PreIncrement has HoldFirst. Now ++(++x) evaluates ++x first yielding 2, then evaluates (++x) = 2+1 resulting in an error (trying to assign to PreIncrement) and returning 3. This also explains why ...


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