# Tag Info

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

55

Point #1 Part always wraps element sequences with the original head of the expression. expr = Hold[1 + 1, 2 + 2, 3 + 3, 4 + 4, 5 + 5]; expr[[{2, 3}]] Hold[2 + 2, 3 + 3] For this purpose a single part e.g. 1 is not a sequence but {1} and 1 ;; 1 are: expr[[1]] expr[[{1}]] expr[[1 ;; 1]] 2 Hold[1 + 1] Hold[1 + 1] This applies at every level of the ...

53

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

38

I already answered this question on StackOverflow but since old questions can no longer be migrated without undue trouble I shall reproduce my answer here. There are two different categories of graphical objects in a Plot output. The plotted lines of the functions (Sin[x], Cos[x]) and their styles are "hard coded" into Line objects, which Graphics can ...

31

Ah well... this is not robust, but probably of educational value and useful as a starting point for other post-processing needs on Graphics or Graphics3D expressions: p = Plot[Sin[x], {x, 0, 1}] col = Cases[p, _Hue, Infinity][[1]]; Show[p /. col -> Red] Update: As pointed out by matheorem, Version 10 switched from Hue to RGBColor, so 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, "...

28

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

27

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] *) ...

26

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

25

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

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

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

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}]];...

22

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

22

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]

21

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

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

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

19

I thought of this question while on the train but the solution appeared in my brain as soon as I got into work. All you need to do is create a ComplexityFunction that includes a side effect f[x_] := (Print[x]; LeafCount[x]) Simplify[TrigExpand[Tan[x + y]], ComplexityFunction -> f] This gives the following output (Cos[y] Sin[x])/(Cos[x] Cos[y]-Sin[...

19

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] ; &...

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

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

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

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

16

y = a[b, c][d]; y[[0, 0]] = w; y (* w[b, c][d] *)

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