Add standard env

This commit is contained in:
Seviche CC 2023-06-10 23:51:37 +08:00
parent fff575908c
commit 544e0951f1
Signed by: SevicheCC
GPG key ID: C577000000000000
2 changed files with 135 additions and 20 deletions

View file

@ -1,7 +1,9 @@
## (c) Peter Norvig, 2010-16; See http://norvig.com/lispy.html
# (c) Peter Norvig, 2010-16; See http://norvig.com/lispy.html
import math
import operator as op
program = "(begin (define r 10) (* pi (* r r)))"
################ Types
# Types
Symbol = str
List = list
@ -10,16 +12,19 @@ Atom = (Symbol, Number)
Exp = (Atom, list)
Env = dict
################ Parsing: parse, tokenize, and read_from_tokens
# Parsing: parse, tokenize, and read_from_tokens
def parse(program:str) -> Exp:
def parse(program: str) -> Exp:
"Read a Scheme expression from a string."
return read_from_tokens(tokenize(program))
def tokenize(chars: str) -> list:
"Convert a string of characters into list of tokens."
return chars.replace('(', ' ( ').replace(')', ' ) ').split()
def read_from_tokens(tokens: list) -> Exp:
"Read an expression from a sequence of tokens."
if len(tokens) == 0:
@ -36,12 +41,49 @@ def read_from_tokens(tokens: list) -> Exp:
else:
return atom(token)
def atom(token: str) -> Atom:
"Numbers become numbers; every other token is a symbol."
try: return int(token)
try:
return int(token)
except ValueError:
try: return float(token)
try:
return float(token)
except ValueError:
return Symbol(token)
print(parse(program))
# Environments
def standard_env() -> Env:
'An environment with some Scheme standard procedures'
env = Env()
env.update(vars(math))
env.update({
'+': op.add, '-': op.sub, '*': op.mul, '/': op.truediv,
'>': op.gt, '<': op.lt, '>=': op.ge, '<=': op.le, '=': op.eq,
'abs': abs,
'append': op.add,
'apply': lambda proc, args: proc(args),
'begin': lambda *x: x[-1],
'car': lambda x: x[0],
'cdr': lambda x: x[1:],
'cons': lambda x, y: [x]+y,
'eq?': op.is_,
'equal?': op.eq,
'expt': pow,
'length': len,
'list': lambda *x: list(x),
'list?': lambda x: isinstance(x, List),
'map': map,
'max': max,
'min': min,
'not': op.not_,
'null?': lambda x: x == [],
'number?': lambda x : isinstance(x, Number),
'print': print,
'procedure?': callable,
'round': round,
'symbol?': lambda x : isinstance(x, Symbol)
})
return env
global_env = standard_env()

View file

@ -1,19 +1,51 @@
// Lispts: Scheme Interpreter in TypeScript
const program = "(begin (define r 10) (* pi (* r r)))"
type LSymbol = string // A Lisp Symbol(alias TSymbol) is implemented as TypeScript string
// types
type LSymbolType = string // A Lisp Symbol(alias TSymbol) is implemented as TypeScript string
type LNumber = number // A Lisp Symbol(alias TSymbol) is implemented as TypeScript number
type Atom = LSymbol | number // A Lisp Atom is a Symbol or Number impl
type Atom = LSymbolType | number // A Lisp Atom is a Symbol or Number impl
type List = Array<any> // A Lisp List is implemented as a TypeScript array
type Exp = Atom | List // A Lisp expression is an Atom or List
interface Env {
[key: string | number]: any
} // A Lisp environment is a mapping of {variable: value}
type Env = Map<string, any>;
class LSymbol {
readonly value: string;
constructor(value: string) {
this.value = value;
}
toString(): string {
return this.value;
}
}
// utils
const deepEqual = (a: any, b: any): boolean =>{
if(a=== b) return true
if(typeof a !== 'object'|| typeof b !== 'object' || a === null || b === null )
return false
const keyA = Object.keys(a)
const keyB = Object.keys(b)
if(keyA.length !== keyB.length) return false
for(const key of keyA){
if(!keyB.includes(key) || !deepEqual(a[key], b[key])) return false
}
return true
}
/**
* Read a Scheme expression from a string.
*/
const parse = (program: string): Exp => read_from_tokens(tokenize(program))
const parse = (program: string): Exp => readFromTokens(tokenize(program))
/**
* Convert a string into a list of tokens.
@ -29,20 +61,20 @@ const tokenize = (char: string): string[] =>
* Numbers become numbers; every other token is a symbol(LSymbol).
*/
const atom = (token: string): Atom =>
Number.isNaN(token) ? Number(token) : (token as LSymbol)
isNaN(Number(token)) ? token as LSymbolType : Number(token)
/**
/**
* Read an expression from a sequence of tokens
*/
const read_from_tokens = (tokens: string[]): Exp => {
if (tokens.length === 0 || !tokens) {
const readFromTokens = (tokens: string[]): Exp => {
if (tokens.length === 0) {
throw new Error('unexpected EOF while reading')
}
const token = tokens.shift()
if (token === '(') {
const l = []
while (tokens[0] !== ')') {
l.push(read_from_tokens(tokens))
l.push(readFromTokens(tokens))
}
tokens.shift()
return l
@ -53,4 +85,45 @@ const read_from_tokens = (tokens: string[]): Exp => {
}
}
console.log(parse(program))
// Environments
/**
* An environment with some Scheme standard procedures
*/
const standardEnv = (): Env => {
let env: Env = new Map()
env.set('+', (a: number, b: number) => a + b)
env.set('-', (a: number, b: number) => a - b)
env.set('*', (a: number, b: number) => a * b)
env.set('/', (a: number, b: number) => a / b)
env.set('>', (a: number, b: number) => a > b)
env.set('<', (a: number, b: number) => a < b)
env.set('>=', (a: number, b: number) => a >= b)
env.set('<=', (a: number, b: number) => a <= b)
env.set('=', (a: number, b: number) => a === b)
env.set('abs', Math.abs)
env.set('append', (a: any[], b: any[]) => a.concat(b))
env.set('apply', (proc: Function, args: any[]) => proc(...args))
env.set('begin', (...x: any) => x[x.length - 1])
env.set('car', (...x: any) => x[0])
env.set('cdr', (...x: any) => x.slice(1))
env.set('cons', (x: any, y: any) => [x, ...y])
env.set('eq?', (a: any, b: any) => Object.is(a, b))
env.set('equal?', (a: any, b: any) => deepEqual(a, b))
env.set('expt', Math.pow)
env.set('length', (x: any[]) => x.length)
env.set('list', (...x: any[]) => Array.from(x))
env.set('list?', (x: any) => Array.isArray(x))
env.set('map', Array.prototype.map)
env.set('max', Math.max)
env.set('min', Math.min)
env.set('not', (x: boolean) => !x)
env.set('null?', (x: any[]) => x.length === 0)
env.set('number?', (x: any) => typeof x === 'number')
env.set('print', console.log)
env.set('procedure?', (x: any) => typeof x === 'function')
env.set('round', Math.round)
env.set('symbol?', (x: any) =>x instanceof LSymbol )
return env
}
const globalEnv = standardEnv()