# Tag Info

## Hot answers tagged expression-manipulation

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

57

These three functions are similar (speaking commonly), and in some applications any of them could be used, yet they have very different special applications. Rudimentarily: Map wraps (sub)expressions in a given Head, and returns the modified input Apply replaces Heads in (sub)expressions, and returns the modified input Scan "visits" (sub)expressions, ...

45

You can use custom transformation rules, for example: -11 - 2 x + x^2 - 4 y + y^2 - 6 z + z^2 //. (a : _ : 1)*s_Symbol^2 + (b : _ : 1)*s_ + rest__ :> a (s + b/(2 a))^2 - b^2/(4 a) + rest returns (* -25 + (-1 + x)^2 + (-2 + y)^2 + (-3 + z)^2 *) The above rule does not account for cases where b is zero, but those are easy to add too, if ...

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

29

Although less magical, it can be done by ReplacePart expr = Hold[{2, 3, 4, 5}] pos = Position[expr, _Integer] newparts = Extract[expr, pos] /. n_Integer :> n^2 ReplacePart[expr, Thread[pos -> newparts]]

28

Assuming you don't have any built-in symbols in that list, you could simply do: DeleteDuplicates@Cases[Leff, _Symbol, Infinity] (* {da, ma, dm, mc, La, h, R} *) If you do have symbols from built-in contexts or packages, you can simply pick out only those that are in the Global context with: With[{globalQ = Context@# === "Global" &}, ...

28

Yes. Use SystemPrivateSetNoEntry on any expression which you want to protect in this manner. This works on per-expression basis, so you have to apply this function to any instance which you want to protect. The result is a reference to the same expression. The changes are performed in-place (no copy is created): expr = h[1, 2, 3] (* h[1, 2, 3] *) ...

27

You can actually Delete the head of the expression, which is part 0: Delete[#, 0] & /@ {Cos[a], Sin[b], Tan[c]} {a, b, c} With version 10 operator forms: Delete[0] /@ {Cos[a], Sin[b], Tan[c]} {a, b, c} One case of interest may be held expressions. If our expression is: expr = HoldComplete[2 + 2]; And the head we wish to remove is Plus, we cannot ...

25

You can use Normal, ConditionalExpression is not explicitly mentioned there but documentation says it deals with special forms. p1 = y /. {First[Solve[x^2 + y^2 + x == 1, y, Reals]]} // First ConditionalExpression[-Sqrt[1 - x - x^2], 1/2 (-1 - Sqrt[5]) < x < 1/2 (-1 + Sqrt[5])] Normal @ p1 -Sqrt[1 - x - x^2]

24

Case #1 Observe: "anything" /. Plus[___] -> "match" "match" This is because Plus[___] evaluates to ___, and ___ matches anything. You can use HoldPattern: Sqrt[Plus[x, y]] /. HoldPattern[Plus[___]] -> u Sqrt[u] For this particular case you could also use the form _Plus, which matches any expression with head Plus but not Plus itself: Sqrt[Plus[...

24

I assume you have Maple to use. If so, Simply open Maple and type the Mathematica command itself directly into Maple using the FromMma package built-into Maple, like this: restart; with(MmaTranslator); #load the package (*[FromMma, FromMmaNotebook, Mma, MmaToMaple]*) and now can use it FromMma(Integrate[Cos[x],x]); One can also use Maple convert ...

24

Analysis of the problem All functions in Mathematica either hold one or more of their arguments, or per The Standard Evaluation Procedure the arguments are evaluated before the function is applied. Thread has no HoldFirst attribute therefore it falls into the latter category. Because of this in an expression like Thread[Print[{a, b, c}, " = ", {1, 2, 3}]];...

24

test = a[b[c[d]]]; Fold[ Construct, (* or Compose, see [1] *) Level[test, {-1}, Heads -> True] ] a[b][c][d] [1] - Is there a name for #1@#2&? Alternatively, thanks to OP and Mr.Wizard: HeadCompose @@ Level[test, {-1}, Heads -> True]

23

Implementation The following implementation is based on expression serialization and SequenceAlignment built-in function. The idea is to break expressions into constituent parts, then align these part sequences, and then determine the positions where the expressions are different. The auxiliary heads we will need are inert heads diff and myHold, the latter ...

21

I'm going to take this as a general question, referring to all atomic objects, not just DelaunayMesh. By design, atomic objects like DelaunayMesh, SparseArray, Graph, etc. or even Association and Rational are not meant to be accessed directly as a Mathematica expression. There are various reasons why an object was made atomic, typically related to ...

21

Corrected to use SubscriptBox as Rojo showed and Kvothe commented, fixing binding. Rojo shows a way in Is it possible to define custom compound assignment operators like ⊕= similar to built-ins +=, *= etc? MakeExpression[RowBox[{f_, SubscriptBox["/@", n_], expr_}], StandardForm] := MakeExpression @ RowBox[{"Map", "[", f, ",", expr, ",", "{", n, "}", "]"}...

20

You can use any built in operator modified with subscripts, superscripts, etc, and retain its precedence, for your own purposes. For example, say you want a general Apply operator like @@ that could work at any level. One could use create the operator @@ with a number subscripted for the level of Apply seems appropriate MakeExpression[RowBox[{fun_, ...

19

One way would be to redirect all messages issued by ToExpression to a string-stream. Here is an example of that approach, with minimal error-checking: Needs["Developer"] interpret[str_String] := Module[{s = StreamToString[], r, m} , Block[{\$Messages = {s}}, r = ToExpression[str, InputForm, HoldComplete]] ; m = StringFromStream[s] ; Close[s] ; &...

19

You can use EntityValue to find out what symbols can be atomic: EntityValue[EntityClass["WolframLanguageSymbol", "Atomic"], "CanonicalName"] {"AggregationLayer", "Association", "Audio", "BasicRecurrentLayer", "BatchNormalizationLayer", "BooleanFunction", "BoundaryMeshRegion", "ByteArray", "CatenateLayer", "ColorProfileData", "Complex", "...

18

That's an interesting first question. Welcome. :-) From a simplistic perspective this should work, but as you observe there are evaluation properties that are more complex. Here is a reference for most (but not all) behavior: The Standard Evaluation Sequence Let's follow those steps for your example. Heads are evaluated first Evaluate the head h of ...

18

The following seems to work, however I think it's not general enough: At a clean nb, enter: For[i = 0, i < 4, i++, Print[{i, {33, i}}]] For[i = 0, i < 4, i++, Print[Graphics[Circle[], ImageSize -> 20]]] And then retrieve the Print[ ] output as: c = Cases[NotebookRead /@ Cells[GeneratedCell -> True], Cell[___, "Print", ___]]; ToExpression /@ ...

18

There seems to be a subtlety in the way delayed rules are used. Have a look at the following: {a,a,a} /. a/;(Print["lhs evaluated"];True) :>(Print["rhs valuated"]; RandomReal[]) (*lhs evaluated lhs evaluated lhs evaluated rhs evaluated rhs evaluated rhs evaluated *) (* {0.797753,0.567294,0.91182} *) This shows that when we use a delayed rule ...

18

First, let me tell you that my answer here is by no means a replacement for the trickier, but more capable implementation of Mr. Wizard. What I want to show is that the examples I point out at the end can be handled with a shorter approach. Keep this in mind. For a new user of Mathematica, the implementation below might serve as a starting point in ...

18

I have a new package for speeding up the construction of things like these which I discuss at the end Atomic vs Valid These are two related but distinct concepts. The former indicates that we can't access subparts of the expression. The second indicates that the expression has already fed through its entire constructor process and we don't need to update ...

17

As far as I know, there is no easy, general way to handle this kind of algebra with Sum expressions. What follows is an attempt to use replacement rules to handle a wider range of cases than chris's example. I don't consider it to be the canonical answer that is required, but perhaps someone might be able to use it as a starting point. I use Inactive on ...

16

As Mr.Wizard indicated, you can also reconstruct the plot using the data. Here is an example: restylePlot2[p_, op : OptionsPattern[ListLinePlot]] := ListLinePlot[Cases[Normal@p, Line[x__] :> x, ∞], op, Options[p]] then we can set the style as we do in plot. For example restylePlot2[myplot2, PlotStyle -> {{Green, Thick, Dashed}, {Thickness[...

16

Using an undocumented function: ReduceFreeVariables[(mc dm^2 + mc/12*(h^2 + 3 R^2) + ma da^2 + ma/12 La^2)/ (mc dm + ma da)] {da, dm, h, La, ma, mc, R}

16

You can open a whole Mathematica notebook in Maple using its Open... menu, and all expressions in the notebook will be converted to Maple representation:

16

According to the documentation of Clear or ClearAll it is possible to provide symbols in form of regular expression (limited), in particular as string with exact symbol name. Clear @@ {"width", "long", "line", "distance"} Let's say there is no possibility to do that, one way would be: Map[Clear, ToExpression[{"width", "long", "line", "distance"}, ...

16

I think this is the simplest fast way to convert an atomic expression to an equivalent compound form, to be able to inspect and manipulate its "apparent" full form: g = RandomGraph[{5,8}]; (* this is our atomic expression *) ml = LinkCreate[LinkMode -> Loopback]; LinkWrite[ml, With[{e = g}, Hold[e]]] LinkRead[ml] LinkClose[ml] (* Hold[Graph[{1, 2, 3, 4,...

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