reading symbols from environments

master
Jordan Orelli 12 years ago
parent b6a88a15fb
commit 7eedbb4e92

@ -0,0 +1,21 @@
package main
import (
"fmt"
)
type UnknownSymbolError struct{ symbol }
func (u UnknownSymbolError) Error() string {
return fmt.Sprintf(`unknown symbol "%v"`, u.symbol)
}
type environment map[symbol]interface{}
func (e environment) get(key symbol) (interface{}, error) {
v, ok := e[key]
if ok {
return v, nil
}
return nil, UnknownSymbolError{key}
}

@ -15,6 +15,12 @@ type sexp []interface{}
type symbol string type symbol string
var universe = environment{
"int": 5,
"float": 3.14,
"string": "Jordan",
}
// parses the string lexeme into a value that can be eval'd // parses the string lexeme into a value that can be eval'd
func atom(t token) (interface{}, error) { func atom(t token) (interface{}, error) {
switch t.t { switch t.t {
@ -84,18 +90,30 @@ func parse(c chan token) (interface{}, error) {
return nil, io.EOF return nil, io.EOF
} }
func eval(v interface{}) { func eval(v interface{}, env environment) error {
fmt.Println(v) switch t := v.(type) {
case symbol:
s, err := env.get(t)
if err != nil {
return err
}
return eval(s, env)
default:
fmt.Println(v)
}
return nil
} }
func evalall(c chan token) { func evalall(c chan token, env environment) {
for { for {
v, err := parse(c) v, err := parse(c)
switch err { switch err {
case io.EOF: case io.EOF:
return return
case nil: case nil:
eval(v) if err := eval(v, env); err != nil {
fmt.Println("error:", err)
}
default: default:
fmt.Println("error in eval: %v", err) fmt.Println("error in eval: %v", err)
} }
@ -113,7 +131,7 @@ func args() {
c := make(chan token, 32) c := make(chan token, 32)
go lex(bufio.NewReader(f), c) go lex(bufio.NewReader(f), c)
evalall(c) evalall(c, universe)
} }
func main() { func main() {
@ -142,6 +160,6 @@ func main() {
c := make(chan token, 32) c := make(chan token, 32)
go lexs(string(line)+"\n", c) go lexs(string(line)+"\n", c)
evalall(c) evalall(c, universe)
} }
} }

Loading…
Cancel
Save