-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patheg_trees.py
61 lines (44 loc) · 1.56 KB
/
eg_trees.py
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
"""
Testing out tree parsing.
"""
from operator import add, sub
from parson import anyone, capture, delay, nest, one_of, one_that
end = ~anyone
def match(p, x): return (p + end)([x])
def an_instance(type_): return one_that(lambda x: isinstance(x, type_))
def capture1(p): return capture(p) >> (lambda x: x[0]) # Ouch
var = capture1(anyone)
## (var + var)(eg)
#. ('+', 2)
calc = delay(lambda:
nest(one_of('+') + calc + calc + end) >> add
| nest(one_of('-') + calc + calc + end) >> sub
| capture1(an_instance(int)))
eg = ['+', 2, 3]
## match(calc, eg)
#. (5,)
eg2 = ['+', ['-', 2, 4], 3]
## match(calc, eg2)
#. (1,)
# Exercise: transforming trees with generic walks
flatten1 = delay(lambda:
nest(one_of('+') + flatten1.star() + end)
| capture1(an_instance(int)))
## match(flatten1, ['+', ['+', ['+', 1, ['+', 2]]]])
#. (1, 2)
# Figure 2.7 in the OMeta thesis, more or less:
def walk(p, q=capture1(an_instance(int))):
return ( nest(one_of('+') + p.star() + end) >> tag('+')
| nest(one_of('-') + p.star() + end) >> tag('-')
| q)
def tag(constant):
return lambda *args: (constant,) + args
flatten2 = delay(lambda:
nest(one_of('+') + flatten2 + end)
| nest(one_of('+') + inside.star() + end) >> tag('+')
| walk(flatten2))
inside = delay(lambda:
nest(one_of('+') + inside.star() + end)
| flatten2)
## match(flatten2, ['+', ['+', ['+', 1, ['+', 2], ['+', 3, 4]]]])
#. (('+', 1, 2, 3, 4),)