-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathpatterns.py
More file actions
1810 lines (1488 loc) · 55.7 KB
/
patterns.py
File metadata and controls
1810 lines (1488 loc) · 55.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Rules and Patterns
The concept of transformation rules for arbitrary symbolic patterns is key in Mathics.
Also, functions can get applied or transformed depending on whether or not functions arguments match.
Some examples:
>> a + b + c /. a + b -> t
= c + t
>> a + 2 + b + c + x * y /. n_Integer + s__Symbol + rest_ -> {n, s, rest}
= {2, a, b + c + x y}
>> f[a, b, c, d] /. f[first_, rest___] -> {first, {rest}}
= {a, {b, c, d}}
Tests and Conditions:
>> f[4] /. f[x_?(# > 0&)] -> x ^ 2
= 16
>> f[4] /. f[x_] /; x > 0 -> x ^ 2
= 16
Elements in the beginning of a pattern rather match fewer elements:
>> f[a, b, c, d] /. f[start__, end__] -> {{start}, {end}}
= {{a}, {b, c, d}}
Optional arguments using 'Optional':
>> f[a] /. f[x_, y_:3] -> {x, y}
= {a, 3}
Options using 'OptionsPattern' and 'OptionValue':
>> f[y, a->3] /. f[x_, OptionsPattern[{a->2, b->5}]] -> {x, OptionValue[a], OptionValue[b]}
= {y, 3, 5}
The attributes 'Flat', 'Orderless', and 'OneIdentity' affect pattern matching.
"""
# This tells documentation how to sort this module
sort_order = "mathics.builtin.rules-and-patterns"
from mathics.algorithm.parts import python_levelspec
from mathics.builtin.base import (
AtomBuiltin,
BinaryOperator,
Builtin,
PatternError,
PatternObject,
PostfixOperator,
)
from mathics.builtin.lists import InvalidLevelspecError
from mathics.core.atoms import Integer, Number, Rational, Real, String
from mathics.core.attributes import (
A_HOLD_ALL,
A_HOLD_FIRST,
A_HOLD_REST,
A_PROTECTED,
A_SEQUENCE_HOLD,
)
from mathics.core.element import EvalMixin
from mathics.core.expression import Expression, SymbolVerbatim
from mathics.core.list import ListExpression
from mathics.core.pattern import Pattern, StopGenerator
from mathics.core.rules import Rule
from mathics.core.symbols import Atom, Symbol, SymbolFalse, SymbolList, SymbolTrue
from mathics.core.systemsymbols import SymbolBlank, SymbolDispatch
SymbolDefault = Symbol("Default")
class Rule_(BinaryOperator):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Rule_.html</url>
<dl>
<dt>'Rule[$x$, $y$]'
<dt>'$x$ -> $y$'
<dd>represents a rule replacing $x$ with $y$.
</dl>
>> a+b+c /. c->d
= a + b + d
>> {x,x^2,y} /. x->3
= {3, 9, y}
"""
# TODO: An error message should appear when Rule is called with a wrong
# number of arguments
"""
>> a /. Rule[1, 2, 3] -> t
: Rule called with 3 arguments; 2 arguments are expected.
= a
"""
name = "Rule"
operator = "->"
precedence = 120
attributes = A_SEQUENCE_HOLD | A_PROTECTED
grouping = "Right"
needs_verbatim = True
summary_text = "a replacement rule"
class RuleDelayed(BinaryOperator):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/RuleDelayed.html</url>
<dl>
<dt>'RuleDelayed[$x$, $y$]'
<dt>'$x$ :> $y$'
<dd>represents a rule replacing $x$ with $y$, with $y$ held
unevaluated.
</dl>
>> Attributes[RuleDelayed]
= {HoldRest, Protected, SequenceHold}
"""
attributes = A_SEQUENCE_HOLD | A_HOLD_REST | A_PROTECTED
needs_verbatim = True
operator = ":>"
precedence = 120
summary_text = "a rule that keeps the replacement unevaluated"
def create_rules(rules_expr, expr, name, evaluation, extra_args=[]):
if isinstance(rules_expr, Dispatch):
return rules_expr.rules, False
elif rules_expr.has_form("Dispatch", None):
return Dispatch(rules_expr.elements, evaluation)
if rules_expr.has_form("List", None):
rules = rules_expr.elements
else:
rules = [rules_expr]
any_lists = False
for item in rules:
if item.get_head() in (SymbolList, SymbolDispatch):
any_lists = True
break
if any_lists:
all_lists = True
for item in rules:
if not item.get_head() is SymbolList:
all_lists = False
break
if all_lists:
return (
ListExpression(
*[
Expression(Symbol(name), expr, item, *extra_args)
for item in rules
]
),
True,
)
else:
evaluation.message(name, "rmix", rules_expr)
return None, True
else:
result = []
for rule in rules:
head_name = rule.get_head_name()
if head_name not in ("System`Rule", "System`RuleDelayed"):
evaluation.message(name, "reps", rule)
return None, True
elif len(rule.elements) != 2:
evaluation.message(
# TODO: shorten names here
rule.get_head_name(),
"argrx",
rule.get_head_name(),
3,
2,
)
return None, True
else:
result.append(
Rule(
rule.elements[0],
rule.elements[1],
delayed=(head_name == "System`RuleDelayed"),
)
)
return result, False
class Replace(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Replace.html</url>
<dl>
<dt>'Replace[$expr$, $x$ -> $y$]'
<dd>yields the result of replacing $expr$ with $y$ if it
matches the pattern $x$.
<dt>'Replace[$expr$, $x$ -> $y$, $levelspec$]'
<dd>replaces only subexpressions at levels specified through
$levelspec$.
<dt>'Replace[$expr$, {$x$ -> $y$, ...}]'
<dd>performs replacement with multiple rules, yielding a
single result expression.
<dt>'Replace[$expr$, {{$a$ -> $b$, ...}, {$c$ -> $d$, ...}, ...}]'
<dd>returns a list containing the result of performing each
set of replacements.
</dl>
>> Replace[x, {x -> 2}]
= 2
By default, only the top level is searched for matches
>> Replace[1 + x, {x -> 2}]
= 1 + x
>> Replace[x, {{x -> 1}, {x -> 2}}]
= {1, 2}
Replace stops after the first replacement
>> Replace[x, {x -> {}, _List -> y}]
= {}
Replace replaces the deepest levels first
>> Replace[x[1], {x[1] -> y, 1 -> 2}, All]
= x[2]
By default, heads are not replaced
>> Replace[x[x[y]], x -> z, All]
= x[x[y]]
Heads can be replaced using the Heads option
>> Replace[x[x[y]], x -> z, All, Heads -> True]
= z[z[y]]
Note that heads are handled at the level of elements
>> Replace[x[x[y]], x -> z, {1}, Heads -> True]
= z[x[y]]
You can use Replace as an operator
>> Replace[{x_ -> x + 1}][10]
= 11
"""
messages = {
"reps": "`1` is not a valid replacement rule.",
"rmix": "Elements of `1` are a mixture of lists and nonlists.",
}
options = {"Heads": "False"}
rules = {"Replace[rules_][expr_]": "Replace[expr, rules]"}
summary_text = "apply a replacement rule"
def apply_levelspec(self, expr, rules, ls, evaluation, options):
"Replace[expr_, rules_, Optional[Pattern[ls, _?LevelQ], {0}], OptionsPattern[Replace]]"
try:
rules, ret = create_rules(rules, expr, "Replace", evaluation)
if ret:
return rules
heads = self.get_option(options, "Heads", evaluation) is SymbolTrue
result, applied = expr.do_apply_rules(
rules,
evaluation,
level=0,
options={"levelspec": python_levelspec(ls), "heads": heads},
)
return result
except InvalidLevelspecError:
evaluation.message("General", "level", ls)
except PatternError:
evaluation.message("Replace", "reps", rules)
class ReplaceAll(BinaryOperator):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/ReplaceAll.html</url>
<dl>
<dt>'ReplaceAll[$expr$, $x$ -> $y$]'
<dt>'$expr$ /. $x$ -> $y$'
<dd>yields the result of replacing all subexpressions of
$expr$ matching the pattern $x$ with $y$.
<dt>'$expr$ /. {$x$ -> $y$, ...}'
<dd>performs replacement with multiple rules, yielding a
single result expression.
<dt>'$expr$ /. {{$a$ -> $b$, ...}, {$c$ -> $d$, ...}, ...}'
<dd>returns a list containing the result of performing each
set of replacements.
</dl>
>> a+b+c /. c->d
= a + b + d
>> g[a+b+c,a]/.g[x_+y_,x_]->{x,y}
= {a, b + c}
If $rules$ is a list of lists, a list of all possible respective
replacements is returned:
>> {a, b} /. {{a->x, b->y}, {a->u, b->v}}
= {{x, y}, {u, v}}
The list can be arbitrarily nested:
>> {a, b} /. {{{a->x, b->y}, {a->w, b->z}}, {a->u, b->v}}
= {{{x, y}, {w, z}}, {u, v}}
>> {a, b} /. {{{a->x, b->y}, a->w, b->z}, {a->u, b->v}}
: Elements of {{a -> x, b -> y}, a -> w, b -> z} are a mixture of lists and nonlists.
= {{a, b} /. {{a -> x, b -> y}, a -> w, b -> z}, {u, v}}
ReplaceAll also can be used as an operator:
>> ReplaceAll[{a -> 1}][{a, b}]
= {1, b}
#> a + b /. x_ + y_ -> {x, y}
= {a, b}
ReplaceAll replaces the shallowest levels first:
>> ReplaceAll[x[1], {x[1] -> y, 1 -> 2}]
= y
"""
grouping = "Left"
needs_verbatim = True
operator = "/."
precedence = 110
messages = {
"reps": "`1` is not a valid replacement rule.",
"rmix": "Elements of `1` are a mixture of lists and nonlists.",
}
rules = {"ReplaceAll[rules_][expr_]": "ReplaceAll[expr, rules]"}
summary_text = "apply a replacement rule on each subexpression"
def apply(self, expr, rules, evaluation):
"ReplaceAll[expr_, rules_]"
try:
rules, ret = create_rules(rules, expr, "ReplaceAll", evaluation)
if ret:
return rules
result, applied = expr.do_apply_rules(rules, evaluation)
return result
except PatternError:
evaluation.message("Replace", "reps", rules)
class ReplaceRepeated(BinaryOperator):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/ReplaceRepeated.html</url>
<dl>
<dt>'ReplaceRepeated[$expr$, $x$ -> $y$]'
<dt>'$expr$ //. $x$ -> $y$'
<dd>repeatedly applies the rule '$x$ -> $y$' to $expr$ until
the result no longer changes.
</dl>
>> a+b+c //. c->d
= a + b + d
>> f = ReplaceRepeated[c->d];
>> f[a+b+c]
= a + b + d
>> Clear[f];
Simplification of logarithms:
>> logrules = {Log[x_ * y_] :> Log[x] + Log[y], Log[x_ ^ y_] :> y * Log[x]};
>> Log[a * (b * c) ^ d ^ e * f] //. logrules
= Log[a] + Log[f] + (Log[b] + Log[c]) d ^ e
'ReplaceAll' just performs a single replacement:
>> Log[a * (b * c) ^ d ^ e * f] /. logrules
= Log[a] + Log[f (b c) ^ d ^ e]
"""
grouping = "Left"
needs_verbatim = True
operator = "//."
precedence = 110
messages = {
"reps": "`1` is not a valid replacement rule.",
"rmix": "Elements of `1` are a mixture of lists and nonlists.",
}
options = {
"MaxIterations": "65535",
}
rules = {
"ReplaceRepeated[rules_][expr_]": "ReplaceRepeated[expr, rules]",
}
summary_text = "iteratively replace until the expression does not change anymore"
def apply_list(self, expr, rules, evaluation, options):
"ReplaceRepeated[expr_, rules_, OptionsPattern[ReplaceRepeated]]"
try:
rules, ret = create_rules(rules, expr, "ReplaceRepeated", evaluation)
except PatternError:
evaluation.message("Replace", "reps", rules)
return None
if ret:
return rules
maxit = self.get_option(options, "MaxIterations", evaluation)
if maxit.is_numeric(evaluation):
maxit = maxit.get_int_value()
else:
maxit = -1
while True:
evaluation.check_stopped()
if maxit == 0:
break
maxit -= 1
result, applied = expr.do_apply_rules(rules, evaluation)
if applied:
result = result.evaluate(evaluation)
if applied and not result.sameQ(expr):
expr = result
else:
break
return result
class ReplaceList(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/ReplaceList.html</url>
<dl>
<dt>'ReplaceList[$expr$, $rules$]'
<dd>returns a list of all possible results of applying $rules$
to $expr$.
</dl>
Get all subsequences of a list:
>> ReplaceList[{a, b, c}, {___, x__, ___} -> {x}]
= {{a}, {a, b}, {a, b, c}, {b}, {b, c}, {c}}
You can specify the maximum number of items:
>> ReplaceList[{a, b, c}, {___, x__, ___} -> {x}, 3]
= {{a}, {a, b}, {a, b, c}}
>> ReplaceList[{a, b, c}, {___, x__, ___} -> {x}, 0]
= {}
If no rule matches, an empty list is returned:
>> ReplaceList[a, b->x]
= {}
Like in 'ReplaceAll', $rules$ can be a nested list:
>> ReplaceList[{a, b, c}, {{{___, x__, ___} -> {x}}, {{a, b, c} -> t}}, 2]
= {{{a}, {a, b}}, {t}}
>> ReplaceList[expr, {}, -1]
: Non-negative integer or Infinity expected at position 3.
= ReplaceList[expr, {}, -1]
Possible matches for a sum:
>> ReplaceList[a + b + c, x_ + y_ -> {x, y}]
= {{a, b + c}, {b, a + c}, {c, a + b}, {a + b, c}, {a + c, b}, {b + c, a}}
"""
messages = {
"reps": "`1` is not a valid replacement rule.",
"rmix": "Elements of `1` are a mixture of lists and nonlists.",
}
summary_text = "list of possible replacement results"
def apply(self, expr, rules, max, evaluation):
"ReplaceList[expr_, rules_, max_:Infinity]"
if max.get_name() == "System`Infinity":
max_count = None
else:
max_count = max.get_int_value()
if max_count is None or max_count < 0:
evaluation.message("ReplaceList", "innf", 3)
return
try:
rules, ret = create_rules(
rules, expr, "ReplaceList", evaluation, extra_args=[max]
)
except PatternError:
evaluation.message("Replace", "reps", rules)
return None
if ret:
return rules
list = []
for rule in rules:
result = rule.apply(expr, evaluation, return_list=True, max_list=max_count)
list.extend(result)
return ListExpression(*list)
class PatternTest(BinaryOperator, PatternObject):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/PatternTest.html</url>
<dl>
<dt>'PatternTest[$pattern$, $test$]'
<dt>'$pattern$ ? $test$'
<dd>constrains $pattern$ to match $expr$ only if the
evaluation of '$test$[$expr$]' yields 'True'.
</dl>
>> MatchQ[3, _Integer?(#>0&)]
= True
>> MatchQ[-3, _Integer?(#>0&)]
= False
>> MatchQ[3, Pattern[3]]
: First element in pattern Pattern[3] is not a valid pattern name.
= False
"""
arg_counts = [2]
operator = "?"
precedence = 680
summary_text = "match to a pattern conditioned to a test result"
def init(self, expr):
super(PatternTest, self).init(expr)
# This class has an important effect in the general performance,
# since all the rules that requires specify the type of patterns
# call it. Then, for simple checks like `NumberQ` or `NumericQ`
# it is important to have the fastest possible implementation.
# To to this, we overwrite the match method taking it from the
# following dictionary. Here also would get some advantage by
# singletonizing the Symbol class and accessing this dictionary
# using an id() instead a string...
match_functions = {
"System`AtomQ": self.match_atom,
"System`StringQ": self.match_string,
"System`NumericQ": self.match_numericq,
"System`NumberQ": self.match_numberq,
"System`RealNumberQ": self.match_real_numberq,
"Internal`RealValuedNumberQ": self.match_real_numberq,
"System`Posive": self.match_positive,
"System`Negative": self.match_negative,
"System`NonPositive": self.match_nonpositive,
"System`NonNegative": self.match_nonnegative,
}
self.pattern = Pattern.create(expr.elements[0])
self.test = expr.elements[1]
testname = self.test.get_name()
self.test_name = testname
match_function = match_functions.get(testname, None)
if match_function:
self.match = match_function
def match_atom(self, yield_func, expression, vars, evaluation, **kwargs):
def yield_match(vars_2, rest):
items = expression.get_sequence()
# Here we use a `for` loop instead an all over iterator
# because in Cython this is faster, since it avoids a function
# call. For pure Python, it is the opposite.
for item in items:
if not isinstance(item, Atom):
break
else:
yield_func(vars_2, None)
self.pattern.match(yield_match, expression, vars, evaluation)
def match_string(self, yield_func, expression, vars, evaluation, **kwargs):
def yield_match(vars_2, rest):
items = expression.get_sequence()
for item in items:
if not isinstance(item, String):
break
else:
yield_func(vars_2, None)
self.pattern.match(yield_match, expression, vars, evaluation)
def match_numberq(self, yield_func, expression, vars, evaluation, **kwargs):
def yield_match(vars_2, rest):
items = expression.get_sequence()
for item in items:
if not isinstance(item, Number):
break
else:
yield_func(vars_2, None)
self.pattern.match(yield_match, expression, vars, evaluation)
def match_numericq(self, yield_func, expression, vars, evaluation, **kwargs):
def yield_match(vars_2, rest):
items = expression.get_sequence()
for item in items:
if not (isinstance(item, Number) or item.is_numeric(evaluation)):
break
else:
yield_func(vars_2, None)
self.pattern.match(yield_match, expression, vars, evaluation)
def match_real_numberq(self, yield_func, expression, vars, evaluation, **kwargs):
def yield_match(vars_2, rest):
items = expression.get_sequence()
for item in items:
if not isinstance(item, (Integer, Rational, Real)):
break
else:
yield_func(vars_2, None)
self.pattern.match(yield_match, expression, vars, evaluation)
def match_positive(self, yield_func, expression, vars, evaluation, **kwargs):
def yield_match(vars_2, rest):
items = expression.get_sequence()
if all(
isinstance(item, (Integer, Rational, Real)) and item.value > 0
for item in items
):
yield_func(vars_2, None)
self.pattern.match(yield_match, expression, vars, evaluation)
def match_negative(self, yield_func, expression, vars, evaluation, **kwargs):
def yield_match(vars_2, rest):
items = expression.get_sequence()
if all(
isinstance(item, (Integer, Rational, Real)) and item.value < 0
for item in items
):
yield_func(vars_2, None)
self.pattern.match(yield_match, expression, vars, evaluation)
def match_nonpositive(self, yield_func, expression, vars, evaluation, **kwargs):
def yield_match(vars_2, rest):
items = expression.get_sequence()
if all(
isinstance(item, (Integer, Rational, Real)) and item.value <= 0
for item in items
):
yield_func(vars_2, None)
self.pattern.match(yield_match, expression, vars, evaluation)
def match_nonnegative(self, yield_func, expression, vars, evaluation, **kwargs):
def yield_match(vars_2, rest):
items = expression.get_sequence()
if all(
isinstance(item, (Integer, Rational, Real)) and item.value >= 0
for item in items
):
yield_func(vars_2, None)
self.pattern.match(yield_match, expression, vars, evaluation)
def quick_pattern_test(self, candidate, test, evaluation):
if test == "System`NegativePowerQ":
return (
candidate.has_form("Power", 2)
and isinstance(candidate.elements[1], (Integer, Rational, Real))
and candidate.elements[1].value < 0
)
elif test == "System`NotNegativePowerQ":
return not (
candidate.has_form("Power", 2)
and isinstance(candidate.elements[1], (Integer, Rational, Real))
and candidate.elements[1].value < 0
)
else:
from mathics.builtin.base import Test
builtin = None
builtin = evaluation.definitions.get_definition(test)
if builtin:
builtin = builtin.builtin
if builtin is not None and isinstance(builtin, Test):
return builtin.test(candidate)
return None
def match(self, yield_func, expression, vars, evaluation, **kwargs):
# def match(self, yield_func, expression, vars, evaluation, **kwargs):
# for vars_2, rest in self.pattern.match(expression, vars, evaluation):
def yield_match(vars_2, rest):
testname = self.test_name
items = expression.get_sequence()
for item in items:
item = item.evaluate(evaluation)
quick_test = self.quick_pattern_test(item, testname, evaluation)
if quick_test is False:
break
elif quick_test is True:
continue
# raise StopGenerator
else:
test_expr = Expression(self.test, item)
test_value = test_expr.evaluate(evaluation)
if test_value is not SymbolTrue:
break
# raise StopGenerator
else:
yield_func(vars_2, None)
# try:
self.pattern.match(yield_match, expression, vars, evaluation)
# except StopGenerator:
# pass
def get_match_count(self, vars={}):
return self.pattern.get_match_count(vars)
class Alternatives(BinaryOperator, PatternObject):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Alternatives.html</url>
<dl>
<dt>'Alternatives[$p1$, $p2$, ..., $p_i$]'
<dt>'$p1$ | $p2$ | ... | $p_i$'
<dd>is a pattern that matches any of the patterns '$p1$, $p2$,
...., $p_i$'.
</dl>
>> a+b+c+d/.(a|b)->t
= c + d + 2 t
Alternatives can also be used for string expressions
>> StringReplace["0123 3210", "1" | "2" -> "X"]
= 0XX3 3XX0
#> StringReplace["h1d9a f483", DigitCharacter | WhitespaceCharacter -> ""]
= hdaf
"""
arg_counts = None
needs_verbatim = True
operator = "|"
precedence = 160
summary_text = "match to any of several patterns"
def init(self, expr):
super(Alternatives, self).init(expr)
self.alternatives = [Pattern.create(element) for element in expr.elements]
def match(self, yield_func, expression, vars, evaluation, **kwargs):
for alternative in self.alternatives:
# for new_vars, rest in alternative.match(
# expression, vars, evaluation):
# yield_func(new_vars, rest)
alternative.match(yield_func, expression, vars, evaluation)
def get_match_count(self, vars={}):
range = None
for alternative in self.alternatives:
sub = alternative.get_match_count(vars)
if range is None:
range = list(sub)
else:
if sub[0] < range[0]:
range[0] = sub[0]
if range[1] is None or sub[1] > range[1]:
range[1] = sub[1]
return range
class _StopGeneratorExcept(StopGenerator):
pass
class Except(PatternObject):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Except.html</url>
<dl>
<dt>'Except[$c$]'
<dd>represents a pattern object that matches any expression except those matching $c$.
<dt>'Except[$c$, $p$]'
<dd>represents a pattern object that matches $p$ but not $c$.
</dl>
>> Cases[{x, a, b, x, c}, Except[x]]
= {a, b, c}
>> Cases[{a, 0, b, 1, c, 2, 3}, Except[1, _Integer]]
= {0, 2, 3}
Except can also be used for string expressions:
>> StringReplace["Hello world!", Except[LetterCharacter] -> ""]
= Helloworld
#> StringReplace["abc DEF 123!", Except[LetterCharacter, WordCharacter] -> "0"]
= abc DEF 000!
"""
arg_counts = [1, 2]
summary_text = "match to expressions that do not match with a pattern"
def init(self, expr):
super(Except, self).init(expr)
self.c = Pattern.create(expr.elements[0])
if len(expr.elements) == 2:
self.p = Pattern.create(expr.elements[1])
else:
self.p = Pattern.create(Expression(SymbolBlank))
def match(self, yield_func, expression, vars, evaluation, **kwargs):
def except_yield_func(vars, rest):
raise _StopGeneratorExcept(True)
try:
self.c.match(except_yield_func, expression, vars, evaluation)
except _StopGeneratorExcept:
pass
else:
self.p.match(yield_func, expression, vars, evaluation)
class _StopGeneratorMatchQ(StopGenerator):
pass
class Matcher:
def __init__(self, form):
if isinstance(form, Pattern):
self.form = form
else:
self.form = Pattern.create(form)
def match(self, expr, evaluation):
def yield_func(vars, rest):
raise _StopGeneratorMatchQ(True)
try:
self.form.match(yield_func, expr, {}, evaluation)
except _StopGeneratorMatchQ:
return True
return False
def match(expr, form, evaluation):
return Matcher(form).match(expr, evaluation)
class MatchQ(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/MatchQ.html</url>
<dl>
<dt>'MatchQ[$expr$, $form$]'
<dd>tests whether $expr$ matches $form$.
</dl>
>> MatchQ[123, _Integer]
= True
>> MatchQ[123, _Real]
= False
>> MatchQ[_Integer][123]
= True
>> MatchQ[3, Pattern[3]]
: First element in pattern Pattern[3] is not a valid pattern name.
= False
"""
rules = {"MatchQ[form_][expr_]": "MatchQ[expr, form]"}
summary_text = "test whether an expression matches a pattern"
def apply(self, expr, form, evaluation):
"MatchQ[expr_, form_]"
try:
if match(expr, form, evaluation):
return SymbolTrue
return SymbolFalse
except PatternError as e:
evaluation.message(e.name, e.tag, *(e.args))
return SymbolFalse
class Verbatim(PatternObject):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Verbatim.html</url>
<dl>
<dt>'Verbatim[$expr$]'
<dd>prevents pattern constructs in $expr$ from taking effect,
allowing them to match themselves.
</dl>
Create a pattern matching 'Blank':
>> _ /. Verbatim[_]->t
= t
>> x /. Verbatim[_]->t
= x
Without 'Verbatim', 'Blank' has its normal effect:
>> x /. _->t
= t
"""
arg_counts = [1, 2]
summary_text = "take the pattern elements as literals"
def init(self, expr):
super(Verbatim, self).init(expr)
self.content = expr.elements[0]
def match(self, yield_func, expression, vars, evaluation, **kwargs):
if self.content.sameQ(expression):
yield_func(vars, None)
class HoldPattern(PatternObject):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/HoldPattern.html</url>
<dl>
<dt>'HoldPattern[$expr$]'
<dd>is equivalent to $expr$ for pattern matching, but
maintains it in an unevaluated form.
</dl>
>> HoldPattern[x + x]
= HoldPattern[x + x]
>> x /. HoldPattern[x] -> t
= t
'HoldPattern' has attribute 'HoldAll':
>> Attributes[HoldPattern]
= {HoldAll, Protected}
"""
arg_counts = [1]
attributes = A_HOLD_ALL | A_PROTECTED
summary_text = "took the expression as a literal pattern"
def init(self, expr):
super(HoldPattern, self).init(expr)
self.pattern = Pattern.create(expr.elements[0])
def match(self, yield_func, expression, vars, evaluation, **kwargs):
# for new_vars, rest in self.pattern.match(
# expression, vars, evaluation):
# yield new_vars, rest
self.pattern.match(yield_func, expression, vars, evaluation)
class Pattern_(PatternObject):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Pattern.html</url>
<dl>
<dt>'Pattern[$symb$, $patt$]'
<dt>'$symb$ : $patt$'
<dd>assigns the name $symb$ to the pattern $patt$.
<dt>'$symb$_$head$'
<dd>is equivalent to '$symb$ : _$head$' (accordingly with '__'
and '___').
<dt>'$symb$ : $patt$ : $default$'
<dd>is a pattern with name $symb$ and default value $default$,
equivalent to 'Optional[$patt$ : $symb$, $default$]'.
</dl>
>> FullForm[a_b]
= Pattern[a, Blank[b]]
>> FullForm[a:_:b]
= Optional[Pattern[a, Blank[]], b]
'Pattern' has attribute 'HoldFirst', so it does not evaluate its name:
>> x = 2
= 2
>> x_
= x_
Nested 'Pattern' assign multiple names to the same pattern. Still,
the last parameter is the default value.
>> f[y] /. f[a:b,_:d] -> {a, b}
= f[y]
This is equivalent to:
>> f[a] /. f[a:_:b] -> {a, b}
= {a, b}
'FullForm':
>> FullForm[a:b:c:d:e]
= Optional[Pattern[a, b], Optional[Pattern[c, d], e]]
>> f[] /. f[a:_:b] -> {a, b}
= {b, b}
"""
name = "Pattern"
arg_counts = [2]
attributes = A_HOLD_FIRST | A_PROTECTED
messages = {
"patvar": "First element in pattern `1` is not a valid pattern name.",
"nodef": (