-
Notifications
You must be signed in to change notification settings - Fork 1
/
rpn
executable file
·97 lines (84 loc) · 1.55 KB
/
rpn
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
#!/bin/rc
# A reverse polish 'calculator'. Really, it can do whatever you want with the stack.
# Written 'top-down' - the main function is at the top.
enabled = (+ - . : % pop)
fn %parse {
# An internal operator, prefixed with % to prevent collision.
for(n) {
if (~ $n $enabled) $n
if not push $n
}
}
fn %buf {
# An internal operator, prefixed with % to prevent collision.
gg = ()
while (!~ $1 $#gg) gg = (gg $gg)
$2 = $gg
}
# The most basic of operators.
fn push {
stack = ($"* $stack)
}
fn pop {
'*' = $stack
shift 1
stack = $*
}
fn + {
%buf $stack(1) one
%buf $stack(2) two
res = ($one $two)
pop;pop
push $#res
}
fn - {
%buf $stack(2) one
'*' = $one
shift $stack(1)
pop;pop
push $#*
}
fn x {
tot = 0
count = ()
while(!~ $#count $stack(1)) {
%buf $tot a
%buf $stack(2) b
c = ($a $b)
tot = $#c
count = ($count m)
}
pop;pop
push $tot
}
fn . {
# No hacks here. This is portable.
echo $stack(1)
}
fn : {
count = ()
dividend = $stack(2)
divisor = $stack(1)
%buf $dividend tmp
'*' = $tmp tmp = ()
while (@shift $divisor >[2]/dev/null) {
shift $divisor
count = ($count m)
}
pop;pop
push $#count
}
fn % {
count = ()
dividend = $stack(2)
divisor = $stack(1)
%buf $dividend tmp
'*' = $tmp tmp = ()
while (@shift $divisor >[2]/dev/null) {
shift $divisor
count = ($count m)
}
pop;pop
push $#*
}
%parse $*