-
Notifications
You must be signed in to change notification settings - Fork 0
/
prim.py
71 lines (53 loc) · 1.26 KB
/
prim.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
62
63
64
65
66
67
68
69
70
71
'''
TODO:
* funcs of different arity
* read, display, etc
'''
import operator
from parse import parse
from reg import fetch, assign, FUNC, ARGL, VAL
# primitive i/o
ARITY_0 = {
'read' : lambda: parse(input()),
}
ARITY_1 = {
'show' : print,
'car' : lambda p: p[0],
'cdr' : lambda p: p[1:], # cdr must be a list
}
ARITY_2 = {
'cons' : lambda a, d: [a] + d,
# primitive arithmetic
'_+' : operator.add,
'_*' : operator.mul,
'_-' : operator.sub,
'_/' : operator.floordiv,
'=' : operator.eq,
'<' : operator.lt,
'>' : operator.gt,
}
def is_primitive(var):
try:
return any(
var in primitives for primitives in
[ARITY_0, ARITY_1, ARITY_2]
)
except TypeError:
return False
def is_primitive_func():
return is_primitive(fetch(FUNC))
# prim funcs assumed to take two args
def apply_primitive_func():
func = fetch(FUNC)
if func in ARITY_0:
prim = ARITY_0[func]
result = prim()
if func in ARITY_1:
prim = ARITY_1[func]
arg1, = fetch(ARGL)
result = prim(arg1)
if func in ARITY_2:
prim = ARITY_2[func]
arg1, arg2 = fetch(ARGL)
result = prim(arg1, arg2)
assign(VAL, result)