-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpn.go
160 lines (135 loc) · 2.46 KB
/
rpn.go
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
// Copyright 2013 The Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"io"
"os"
"reflect"
"strconv"
)
type operator func(int) operator
var operators map[string]operator
func init() {
// Do this in init() to avoid
// initialization loop
operators = map[string]operator{
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
"|": or,
"&": and,
"c": negate,
"~": not,
"dup": dup,
"print": print,
"pop": pop,
"swap": swap,
"zero": zero,
}
}
func main() {
for {
fmt.Print("> ")
op := input()
if !sameFunc(op, zero) {
fmt.Println("Error: stack bottomed out")
}
}
}
func input() operator {
var s string
var n int
for {
_, err := fmt.Scan(&s)
if err == io.EOF {
fmt.Println()
os.Exit(0)
}
n, err = strconv.Atoi(s)
if err != nil {
if s == "quit" {
os.Exit(0)
}
op, ok := operators[s]
if ok {
return op
} else {
fmt.Printf("Unrecognized command: %s\n", s)
fmt.Print("> ")
}
} else {
break
}
}
return number(n)
}
func number(i int) operator {
op := input()
return op(i)
}
func add(top int) operator {
return func(bottom int) operator {
return number(bottom + top)
}
}
func subtract(top int) operator {
return func(bottom int) operator {
return number(bottom - top)
}
}
func multiply(top int) operator {
return func(bottom int) operator {
return number(bottom * top)
}
}
func divide(top int) operator {
return func(bottom int) operator {
return number(bottom / top)
}
}
func or(top int) operator {
return func(bottom int) operator {
return number(bottom | top)
}
}
func and(top int) operator {
return func(bottom int) operator {
return number(bottom & top)
}
}
func negate(i int) operator {
return number(-i)
}
func not(i int) operator {
return number(^i)
}
func print(i int) operator {
fmt.Println(i)
fmt.Print("> ")
return number(i)
}
func dup(i int) operator {
op := number(i)
return op(i)
}
func swap(top int) operator {
return func(bottom int) operator {
op := number(bottom)
return op(top)
}
}
func pop(top int) operator {
return func(bottom int) operator {
return number(bottom)
}
}
func zero(i int) operator {
return zero
}
func sameFunc(i, j operator) bool {
// Credit to http://stackoverflow.com/a/18067479/836390
return reflect.ValueOf(i).Pointer() == reflect.ValueOf(j).Pointer()
}