Tag Info

Hot answers tagged

17

Edit: It was pointed out that the original form is not bullet-proof, e.g. GraphicsPrimitiveQ /@ {InputNotebook, Unique, Sequence} all returned True. However, when looking upon this answer about generating new graphics primitives, a superior answer came to light: Clear[GraphicsPrimitiveQ]; GraphicsPrimitiveQ[s_Symbol | (s_)[___]] := 0 < ...


10

To match your literal request you need Alternatives rather than Or. Either x : (_Integer | _Real) or x_Integer | x_Real will work. Following what Szabolcs and "Guess who it is" wrote you might define a realQ like so: realQ = NumericQ[#] && Im[#] == 0 &; f[x_?realQ] := x^2 f /@ {1, Pi, 1.3, 2/3, x^2, 7.1 - 2.8 I} {1, π^2, 1.69, 4/9, f[x^2], ...


10

You can test whether braces are balanced with something like (version simplified by Guess who it is.): ClearAll[balancedBracesQ] balancedBracesQ[str_String] := StringCount[str, "{"] === StringCount[str, "}"] And use it in string pattern in following way: StringCases[ "a\\newcommand{ABC{asdas}{asdsad}}{DEF{x}y}asdkashdkj\ ...


9

I suppose that the set of answers won't be complete without the contribution of a cryptic RegularExpression... $pattern = RegularExpression["\\\\newcommand({([^{}]|(?1))*})(?1)"]; The pattern works for simple cases: StringCases[#, $pattern]& @ "XXX\\newcommand{ABC}{DEF}XXX\\newcommand{GHI}{JKL}XXX\\newcommand{MNO}{PQR}" (* { ...


8

The answer to the question depends upon what exactly should be called as "graphics primitive". In this answer from the practical point of view I define it as a container which can be found inside of Graphics or Graphics3D, which draws something and is not a graphical directive or Dynamic wrapper. This definition differs from the usual meaning but covers all ...


8

This bug has been fixed in version 10.2. $Version (* "10.2.0 for Linux x86 (64-bit) (July 6, 2015)" *) matchLists[patt_] := MatchQ[#, patt] & /@ {{}, {1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}} matchLists[{_ | PatternSequence[]}] matchLists[{x_ | PatternSequence[]}] (* {True, True, False, False, False} *) (* {True, True, False, False, False} *) ...


7

If you are only ever going to call it as f[a^b] (that is, f[Power[a,b]]), you want to look at the attribute HoldFirst (or HoldAll or similar). Specifically: SetAttributes[f, HoldFirst]; f[a_^2] := a Alternatively, SetAttributes[f, HoldFirst]; f[x_] := Unevaluated[x] /. {a_^2 :> a} I'm always wary of using Unevaluated, though. Edited to add: ...


7

Here is one way: lines={"123","312","anb","452","Xys"} ReleaseHold[ lines //. {bef___, PatternSequence[x_String, m_String?(StringFreeQ[#, DigitCharacter] &)], aft___} :> {bef, {Hold[x], m}, aft}] (* ==> {"123", {"312", "anb"}, {"452", "Xys"}} *) I changed the pattern so that it tests the Head of x and m as well, and wrap x in ...


7

Since there seems no other simple answer at this time I propose the approach of rendering a Graphics expression and seeing if it has errors. By definition this will pass both primitives and directives, as well as inert expressions such as {}. I hope it nevertheless serves some purpose. I rasterize the graphic and look for the tell-tale pink warning color. ...


5

If it's absolutely necessary to use the symbols as you've defined them, here's one option. (I've added FRH to the list to show that it doesn't get matched.) Cases[{RBI, RCD, ASD, FGH, FRH}, a_ /; StringMatchQ[ToString @ a, "R" ~~ ___]] results in {RBI, RCD} which is a list of Symbols (not a list of Strings). Now, there's a problem if you have already ...


5

To directly get the opposite of Alternatives, you could negate each pattern with Except and then negate the Alternatives: also[patts__] := Except[Alternatives @@ Except /@ {patts}] Cases[Range[1, 15, 1/2], _Integer ~also~ _?(# > 10 &)] (* {11, 12, 13, 14, 15} *) Generally some other approach will be simpler, though, as discussed in the comments.


4

This question might end up closed as it is hard to know what was in the minds of the language designers in every case. However I think a reasonable answer can be given here so I shall try. The high-level Mathematica language is arguably built on pattern matching. It it therefore natural that many functions also use, operate on, or work with patterns. For ...


4

One way to do this: Attributes[f] = {HoldAll}; f[x_] := ReleaseHold[Hold[x] /. {Power[a_, b_] :> a}]; Then: f[3^2] gives 3. And: f[10000000000000000000000000000000000000000000^1000000000000000] gives 10000000000000000000000000000000000000000000 And: f[10^10^10] gives 10 And: f[(10^10)^10] gives 10000000000 (10^10).


4

I don't know of any direct solution to this problem. I have always had to work around it, but usually I find that isn't too hard. In this case, as I imagine you know, you could just write: StringMatchQ[#, Repeated[__ ~~ " ", {2}] ~~ "17"] & /@ {str1, str2} {True, True} Further this is far more efficient as it is run in an optimized string ...


4

I don't think you can avoid using strings, but that doesn't mean the output will contain strings. Pick[step[2], StringMatchQ[ToString /@ step[2][[All, 1]], "k*p"]] {k1p -> 1.09503, k2p -> 1.32185}


4

It can be done with w.a.b.r + w.c.d.r /. Dot[FRONT_, AA__, BACK_] + Dot[FRONT_, BB__, BACK_] :> Dot[FRONT, Dot[AA] + Dot[BB], BACK] w.(a.b + c.d).r However, I like function argument destructuring, so I would probably write f[Dot[w_, a__, r_] + Dot[w_, b__, r_]] := w.(Dot[a] + Dot[b]).r f[w.a.b.r + w.c.d.r] w.(a.b + c.d).r


4

The documentation states: If no explicit Shortest or Longest is given, ordinary expression patterns are normally effectively assumed to be Shortest[p], while string patterns are assumed to be Longest[p]. Leftmost elements in a sequence of patterns have first priority, and explicit uses of Shortest have priority over this implicit shortest behavior. ...


3

The second one does not work as intended because EvenQ[x] always returns False if x is not "manifestly an even integer" (quote from docs.) Since you use -> instead of :>, the expression If[EvenQ[s], w[s], 0] is evaluated at once, and since s is a symbol at that stage, it is not manifestly an even integer. The first example works because s == 2 is ...


3

I am answering the question in an interesting, thorough way for the reader based on the useful comments I had from other community members. I believe this example is excellent for demonstrating many pattern oriented features inside function definitions. Let me know what you think. Predicate Definition listEmptyQ[lst_List] := Length[lst] == 0 Testing List ...


3

You can use repeated replacement, this will only keep elements that are strictly increasing. list = {1,2,3,4,6,5,7,8}; list = list//. {a___, x_, y_, b___} /; y < x :> {a, x, b} Which gives: {1, 2, 3, 4, 6, 7, 8} In the case that the all elements in Rest@list are less than the first element, a decreasing list for instance, it will return only ...


3

I would use Cases with a condition and SymbolName. Cases[step[2], (symbol_ -> _) /; StringMatchQ[SymbolName[symbol], "k*p"]] Another solution: step[2] /. (symbol_ -> value_) /; Not@StringMatchQ[SymbolName[symbol], "k*p"] :> Nothing This solution makes use of Nothing which is new in Mathematica version 10.2. Nothing could be replaced by ...


3

An approach using ReplaceRepeated and a temporary tag. data = {"DD1", "B12", "CCC", "3AD", "C2A", "3D1", "1A1", "C11", "BBA", "322", "1D2", "B3C", "1BD", "CC1", "AC"}; list //. {bef___, PatternSequence[x_, m_] /; Head[m] =!= tag && StringFreeQ[m, DigitCharacter], aft___} :> {bef, tag[x, m], aft} /. tag -> List ...


3

I'm not sure I correctly interpreted what you really are looking for, because you mention MapThread that works on elements on the same position in the two lists, whereas in the description you say that for each element of list2 you want the closest from list1. Moreover, this means that once you selected an element from list1, it cannot be considered for ...


3

If your pattern is not very big, you could use "brute force". Replace a sub-pattern with more general sub-pattern and check whether pattern matches expression. Repeat it with some subset of possible sub-patterns. This task can be automated using following function. It returns list of pairs. First element of pair is rule replacing position of sub-pattern ...


3

To answer the question as asked, we modify the code as follows: replacementRule = Plus[ Dot[FRONT__, AA__, BACK__] , Dot[FRONT__, BB__, BACK__] ] :> Dot[FRONT, Plus[Dot[AA], Dot[BB]], BACK]}] w.a.b.r + w.c.d.r /. replacementRule First, we have changed -> (Rule) to :> (RuleDelayed) so that when the expression is re-written, it will write it ...


3

Try this: Set[myMatrix[[#, #]], 1] & /@ myIndices; Or: ReplacePart[myMatrix, {{#, #} & /@ myIndices -> 1}] Or: SparseArray[({#, #} -> 1 & /@ myIndices), Dimensions@myMatrix] // Normal


2

The best solution is to use RegionQ, a simple solution suggested by ilian. RegionQ is a function that takes a region as an argument and returns whether it is a valid region. Here is how I used it: regCells = Select[MeshPrimitives[DiscretizedRegion, 3], RegionQ]; This only keeps the regions returned by MeshPrimitives which are valid regions, which allows ...


2

Here is my possibly over-engineered, potentially incomplete approach: string = "asdkashdkj\\newcommand{ABC}{DEF}asdahgsjagsd\\newcommand{ABC}{DwewEF}ahgdajhdgj\\newcommand{ABC}{DEF}\\newcom\\newcommand{ABC{asdas}{asds{}ad}}{DEF}"; step1 = Characters[string] //. { {a___, "{", inside : Except["{" | "}"] ..., "}", b___} :> {a, ...


2

Referencing How to match expressions with a repeating pattern and How to define a recursive pattern? it is in my opinion superior to use a test function definition, which is easily made a pattern with _?test, to using Condition and MatchQ to avoid an infinite loop. It more easily handles the case should one need to keep parts of the expression unevaluated ...


2

I frequently write functions that take one or more arguments which I limit to those quantities that mathematicians call real numbers. In Mathematica that means any quantity satisfying NumericQ excepting complex numbers. To facilitate writing such functions, I define a pattern validNum = Except[_Complex, _?NumericQ]; This pattern is used like so: f[x : ...



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