# Tag Info

37

Between Versions 7 and 8 Hash now gives the hash of a raw sequence of characters when applied to Strings. In past versions the string characters (quotation marks) were included in the calculation of the hash. (Reference) Use "\"" <> string <> "\"" before hashing if you want output to match older versions. \[Dash], \[LongDash] and ...

32

For me the operator forms of Map and Apply will probably provide the most important benefits in terms of code readability. Often I need to apply a sequence of transformations to some data, and I am fond of infix notation for this purpose. For example I find a ~Position~ 0 ~SortBy~ Last more readable than the "conventional" SortBy[Position[a, 0], Last] ...

21

Good News Everyone! Two-parameter syntax for Fold and FoldList has been (silently) implemented! Taliesin Beynon informs me that this was implemented in 2011, so check your older versions as well. As Naitree notes this is now documented in 10.0.2: Fold[f, a] FoldList[f, a] f[f[f[1, 2], 3], 4] {1, f[1, 2], f[f[1, 2], 3], f[f[f[1, 2], 3], 4]} And ...

20

I would have liked to have more experience with the operator forms before this question was asked as I am short on examples, and I'm sure my opinion will evolve over time. Nevertheless I think I have enough familiarity with similar syntax to provide some useful comments. Taliesin Beynon provided some background for this functionality in Chat: Operator ...

18

I see no mention of the new-in-10 PositionIndex in the other answers, which takes a list (or association) of values and returns a 'reverse lookup' that maps from values in the list to the positions where they occur: In[1]:= index = PositionIndex[{a, b, c, a, c, a}] Out[1]= <|a -> {1, 4, 6}, b -> {2}, c -> {3, 5}|> It doesn't take a level ...

15

I find the value of the new operator forms becomes critical when working with datasets. Consider titanic = ExampleData[{"Dataset", "Titanic"}]; titanic[Count[#], "survived"] & /@ {True, False, _Missing} {500, 809, 0} Derive a data set for analyzing the survival of very young passengers. cutoff = 8; youngest = titanic[All, {"age", ...

11

You can have a single rule using Alternatives (|)... {a, b, c, d, e, f, g, h} /. x : (a | c | e | f) -> 12 Furthermore you can construct the rule on the fly... {a, b, c, d, e, f, g, h} /. x : Alternatives@@{a, c, e, f} -> 12 As noted by @Kuba below there is no requirement for the pattern to have a name (x) so... {a, b, c, d, e, f, g, h} /. (a | ...

10

The behaviour we see is due to the precedence of &, which is much lower than the precedence of /@. As a consequence, the expression Line /@ (Print[#]; #) is bound tightly together by the high precedence /@ infix operator, yielding the single argument to the low precedence & postfix operator. This means that the second expression is interpreted as ...

10

This behaviour is very common, possibly near universal, in programming languages with matchfix comment syntax. The reason is that the contents of a comment sequence is presumed not to be code. Usually that presumption is correct, but not in this case. The general rule is You should be able to put anything inside a comment and the only special tokens ...

10

We already have some answers explaining the issue. Let me give a solution to your problem. Let's say you have the code RegularExpression["((re)*)"] that you want to comment out. Since we have nested comments in Mathematica, just use a pair of (* to prevent your issue: Although I don't know the internal implementation of Mathematicas parser, the ...

9

From the docs for Label Label must appear as an explicit element of a CompoundExpression object. So this works: p[1] = .9; i = 1; Label[begin]; i++; p[i] = p[i - 1] + 1; Print[i]; If[i < 5, Goto[begin], Goto[end]]; Label[end]; But this doesn't: p[1] = .9; i = 1; Label[begin]; i++; p[i] = p[i - 1] + 1; Print[i]; If[i < 5, Goto[begin], ...

9

To prevent your second invocation of SetOptions from resetting the value of sub-option "SymbolContextStyles", you need to set both "System" and "Global" sub-sub-option values at once: SetOptions[EvaluationNotebook[], "AutoStyleOptions" -> {"SymbolContextStyles" -> {"System" -> RGBColor[211./255, 54./255, ...

9

A lot of functions in MMA have default values for Optional Arguments, for Example Flatten. It can take Flatten[expr] which means Flatten[expr, Infinity] Some functions don't have such option and you need to feed the Optional Arguments but you can go around by building your own function for your example, you can do this kind of trick like this: f[expr_, ...

8

Very nice answers. I wanted to add something else. One typical "Mathematica way" of coding involves overloading a function with several definitions, that do different things according to what arguments are passed (I actually abuse this). You can pattern match by head with things like f[x_Integer]:=... and f[x_Real]:=.... I see the Dataset/Query ...

8

Also PlotRange[plot] PlotRange /. AbsoluteOptions[plot] Last @@ AbsoluteOptions[plot, PlotRange] PlotRange /. plot[[2]] all give (* {{0.,10.},{-0.999999,1.}} *) Note: Regarding usage of PlotRange as a function, it is undocumented, and the earliest reference I could find on this site is this answer dated Oct 11, 2012: The same range on each plot in a ...

7

The FE only looks at the structure of your code for colouring. It doesn't evaluate anything. This means two things: (1) it can only guess that there might be a problem, because by looking at the structure, it doesn't know whether your code really evaluates to something you might not want. (2) You can easily trick the FE by changing the structure into ...

7

s = {x, y} /. Solve[a x + y == 7 && b x - y == 1, {x, y}][[1]] {8/(a + b), -((a - 7 b)/(a + b))} lsa = LinearSolve[{{a, 1}, {b, -1}}, {7, 1}] {8/(a + b), (-a + 7 b)/(a + b)} f = LinearSolve[{{a, 1}, {b, -1}}]; lsb = f[{7, 1}] // Simplify {8/(a + b), -((a - 7 b)/(a + b))} s == lsa == lsb // Simplify True Solve can handle a ...

7

It comes down to the DRY principle: The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." The content management system Wordpress doesn't use object oriented paradigms and so for that reason it looks exactly like your code. Tens of thousands of lines of code like this. ...

7

tree = Function[x, Defer @ FullForm @ x, HoldAll]; Now: 2 + 2 // tree Plus[2, 2] I used Defer to allow the output to be evaluated. If you do not prefer this replace it with HoldForm. For some explanation of the mechanics of this code see: Why doesn't "Defer" work with "TableForm"? See also my standard methods for ...

7

Differences /@ B or, if you don't like runes, Map[Differences, B] In v10, there is an operator form of Map which can be very useful, Map[Differences] @ B which allows you to slip a Map operation into a sequence of transformations without worrying about precedence issues.

7

As already explained, this happens because MatrixForm act as a wrapper. The answer to the question about how this behavior is implemented and how can eventually be reproduced is contained in the Informmation of the system symbol $OutputForms. Indeed ??$OutputForms returns: \$OutputForms is a list of the formatting functions that get stripped off ...

6

Well, it turns out you are doing the computation with low numerical precision. And this error propagates. If you use high enough precision (infinite maybe), the results turns out fine. Also since you're using a series approximation, including more terms also helps. Here it is: Let's define A: A = {{0, 1}, {-1, -3}}; Then Sum[MatrixPower[20 A, s]/s!, {s, ...

6

Use proper syntax (e.g., Sin[ ] vice Sin( ), Pi vice pi, Normal for Series, Evaluate Plot function to keep from recalculating series expansion for each point). Plot3D[ Evaluate[ Series[ Sin[1 + x + y^2]/(4 + x^2 + y^2), {x, 0, 4}, {y, 0, 7}] // Normal], {x, -Pi, Pi}, {y, -Pi, Pi}, ClippingStyle -> None]

6

Here's another way to achieve the same thing: Differences[{##}] & @@@ B {{1, 1}, {}, {1, 1, 1}} OR for fun Replace[B, x : {__} :> Differences[x], 1]

6

Algohi's answer is the most appropriate if one of the function's arguments is primary and the others secondary. However, you can get closer to the syntax that you suggested in your question using {x^2 + 9 x + 5, 3} // Apply @ PolynomialMod which works in version 10 using the operator form of Apply. Or, to include earlier versions, you could define your ...

6

You should use Sequence PolynomialMod[x^2 + 9 x + 5, 3] PolynomialMod@Sequence[x^2 + 9 x + 5, 3] Sequence[x^2 + 9 x + 5, 3] // PolynomialMod 2 + x^2 all produce the same output. Works with any function Sequence[i, {i, 10}] // Table {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

5

Here's a stab at a second pass: Syntactic sugar shouldn't be underestimated given its cumulative effects (also only a limited number of functions can have shortforms and sometimes for precedence reasons four symbols are needed in the pure form - (#)&) An example: Suppose it is desired to take keys/values "f" through to "h" and "p" through to "r" in ...

5

You could achieve without If, e.g.: f[x_Integer] := StringForm[" is an integer", x]; f[x_] := StringForm["` is not an integer", x]; Test: test = {1, 3, Pi, E, Sqrt[2], Zeta[3], Zeta[-2]} Mapping: Column[f /@ test] yields: Please note IntegerQ[3] is True, however IntegerQ[3.] is False

5

The third parameter allows control of Optional behavior for multiple function definitions. It is not attached to the number of actual arguments passed to the function but rather to the number of arguments that appear in the function definition itself. Consider this example: ClearAll[f]; Default[f, 1, 3] = a1; Default[f, 2, 3] = a2; Default[f, 3, 3] = a3; ...

5

OK, as an after-meal exercise, I fixed your code. The main modifications I've done are: 1. Based on trick mentioned in this post, change your pattern-matching function into pure function. 2. Change qsum = MapThread[Plus, #] &@Rq(for some unclear reason it can't be compiled, maybe it's because Rq isn't a "explicit" list? ) into qsum=Total@Rq. 3. ...

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