Hot answers tagged

29

There is a ToAssociations function in the GeneralUtilities` package that is perfect for this and for converting nested JSON rules to associations: Needs["GeneralUtilities`"] ToAssociations@rdata (* <|"a" -> <|"b" -> 1, "c" -> {7, 8, 9}|>, "d" -> 3|> *) This preserves the inner most list that is not a list of rules. As for your ...


28

General If you are not going to change your list of rules after you construct them, Dispatch is pretty good. From the user's viewpoint, the main difference is that it is cheap to add new key-value pairs to associations, or remove existing ones, constructing new associations. Not so with Dispatch - once you obtained the Dispatch-ed set of rules, you can't ...


22

This is not a bug. However, this is a great opportunity to shed some light on the inner workings of Replace. What happens, in short, is that it first fully processes the expression, without calling main evaluator on any of its replaced parts, and only then the entire transformed expression is given to the evaluator. Basically, we can visualize what happens ...


21

Preamble What happens can be understood when we recall that Rule is a scoping construct. The general issues related to variable renamings in scoping constructs have been considered in more details in this answer. General Now, to this particular case. When the code runs, the external RuleDelayed considers the situation "dangerous" and performs variable ...


19

PositionIndex[assoc][<value>] For example: assoc = <|a -> 1, b -> 2, c -> 3, d -> 1, e -> 4, f -> 1|>; PositionIndex[assoc][1] {a, d, f} And PositionIndex[assoc] <|1 -> {a, d, f}, 2 -> {b}, 3 -> {c}, 4 -> {e}|> Alternatively: PositionIndex[assoc] // Lookup[4] {e}


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


17

Using FullForm, you can see that ImageSize -> 1 -> 1 is the same as ImageSize -> (1 -> 1) i.e., the option value itself is a rule. This appears to be an undocumented shorthand for scaling a graphics to the correct image size or to scale up/down by a factor. Observe the following, using a modified version of the example: img = Import@"http://www....


17

You can also use FilterRules: rule = {beta -> 4, alpha -> 2, x -> 4, z -> 2, w -> 0.8}; FilterRules[rule, beta] (* {beta -> 4} *) FilterRules[rule, {beta, alpha}] (* {beta -> 4, alpha -> 2} *) Update: additional alternatives if you have V10: KeyTake[rule,{alpha, x}] (* or *) KeyTake[{alpha,x}][rule] (* <|alpha->2,x->4|&...


16

One way would be to "invert" the association and then look up values in the result: $a = <| "a" -> 1, "b" -> 2, "c" -> 1, "d" -> 2, "e" -> 3 |>; $inv = $a // Normal // GroupBy[Last -> First] (* <| 1 -> {a, c}, 2 -> {b, d}, 3 -> {e} |> *) $inv[1] (* {a, c} *) If the original collection is a list of rules instead of ...


15

There is no reordering: ReplaceRepeated simply starts replacement from the outside of the expression. For example here the result is not f[g[g[1]]] but: f[f[f[1]]] //. f[f[x_]] :> g[g[x]] (* ==> g[g[f[1]]] *) So in your case, the first rule that is matched is the second one, which happens to be more general (but it has nothing to do with ...


14

Pattern matching is performed based on the form of an expression, not its (mathematical) meaning. Using jargon, pattern matching is performed syntactically, not semantically. Specifically, here x^1 is evaluated/simplified first to be x. The latter no longer has the form of "one thing raised to the power of another thing", so it will not be matched when ...


13

The problem can be seen in simpler expressions: MatchQ[<||>, <||>] (* True *) MatchQ[<||>, HoldPattern[<||>]] (* False *) This behaviour is inconvenient and could be classified as a bug, but... We must take into account the fact that a constructed association object is an atom whereas the expression used to construct an ...


12

m = (3 - I) x + 4 (x y)/(Cos[y]); Variables@Level[m, {-1}] (*{x, y}*)


12

I think the best way to do this is to use Derivative: rules = {func_[τ] /; MemberQ[{f, g, h}, func] :> func[t], Derivative[n_][func_][τ] /; MemberQ[{f, g, h}, func] :> D[func[t[τ]], {τ, n}], Derivative[n_][t][τ] :> D[a[t[τ]], {τ, n - 1}]} The first rule is needed to replace functions of τ with functions of t. The next two rules ...


12

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


12

DeleteCases does not by default operate on heads. You can set the Heads option to True to change that. DeleteCases[{{x -> a}, {x -> b}, {x -> c, x -> d}}, Rule, {3}, Heads -> True] {{x, a}, {x, b}, {x, c, x, d}} Note that the last term has become {x, c, x, d} which is not quite what you expected, but it is logically consistent if we expect ...


11

As István describes this has to do with the traversal direction of //.. ReplaceAll and by extension ReplaceRepeated are very unusual in the context of Mathematica in that they perform a depth-first preorder traversal, whereas nearly all other functions perform a depth-first postorder traversal. Since it is the latter that you want here you merely need to ...


11

First, you really don't want to modify Times, as this will have all sorts of unforeseen side-effects. Your best route will be to use ** (NonCommutativeMultiply), for which you'll have to write rules that enforce the behaviour you want. Here's how you might go about that: genericRules = { (* Move numeric factors outside of NonCommutativeMultiply. *) ...


11

As far as I understand it, once a subexpression gets replaced, it can't get replaced again. Try this: a*b /. {a -> a, a -> 1, b -> c} resulting in a*c The first replacement just replaces a with a, but since that expression has already been changed, it is ignored after that. So the Rule a -> 1 is only applied to other parts of the expression (...


11

Under the Possible Issues tab of the Cases documentation. Use HoldPattern to treat the rule itself as a pattern: Cases[{a -> aa, b -> bb, c -> cc, d -> dd, e -> ee}, HoldPattern[e -> ee]] (*{e -> ee}*)


11

RuleDelayed is unconventional in that it strips any number of occurrences of Unevaluated from the right-hand side: a :> Unevaluated[1 + 1] (* a :> 1 + 1 *) a :> Unevaluated[Unevaluated[Unevaluated[1 + 1]]] (* a :> 1 + 1 *) This is different from the normal evaluation process which only strips one level: ClearAll[f] f[x_] := x f[Unevaluated[...


11

He is simply saying that the first argument of Set is not evaluated before Set creates the definition. However, the sub-parts of the first argument are all evaluated, including the head(i.e. part 0). Thus in f[x] = y f[x] is not evaluated in the sense that any previous definition similar to f[z_] := z^2 will be ignored. However, f is evaluated and x is ...


11

Short Version Order matters when specifying replacement rules. Rules are tried from left-to-right. Each rule will attempt to match and replace as much of the string as possible before moving on to the next rule. Patterns like ___ are very broad and will match anything. More narrowly focused patterns might be more applicable (e.g. Whitespace or Except[...


10

You can use MapAt function to map function on specific part of the expression MapAt[f, {1 -> 2, 2 -> 3, 3 -> 1}, {All, 2}] (* ==> {1 -> f[2], 2 -> f[3], 3 -> f[1]} *) or use replacement rule {1 -> 2, 2 -> 3, 3 -> 1} /. Rule[a_, b_] :> Rule[a, f[b]]


10

This is the shortest I can think of: {list1, list2} = Transpose[List @@@ data]; list1 {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4} list2 {3, 3, 3, 3, 3, 1, 2, 2, 3, 1, 2, 2}


10

The most direct way is to create a dispatch table from your association when you need this behavior: {1, 2, 3} /. Dispatch[Association[{1 -> "test", 2 -> "test", _Integer -> Null}]] (* {"test", "test", Null} *)


10

{{4, 5}, {1, 2}, {1, 5}, {3, 5}} /. {a : ___, b : PatternSequence[{x_, j_}, {x_, k_}], c : ___} :> {a, Sequence @@ Table[{x, j + n (k - j)/3}, {n, 0, 3}], c} (* {{4, 5}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {3, 5}} *) Edit For supporting multiple adjacent values you may do the much more convoluted: g[x_] := Module[{s = 3 Length@x -...


10

To @WReach's examples, one can add these: MatchQ[<||>, Unevaluated@<||>] MatchQ[<||>, HoldPattern[Evaluate@<||>]] (* False True *) It evidently has something to do with the first time an Assocation is evaluated. The following are typeset differently, Hold[#] &@<||> and Hold[<||>], depending on whether the ...


10

There are many ways, here's one: KeyValueMap[#2 -> # &] @ GroupBy[rules, Last -> First, Flatten]


10

You can simply change the Rule -> to RuleDelayed :> to give {_, _, _} /. _Blank :> RandomInteger[{1, 10}] (*{5, 1, 3}*)


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