Skip to content

Instantly share code, notes, and snippets.

@jstejada
Last active October 13, 2015 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstejada/98cbb944793b0df3033b to your computer and use it in GitHub Desktop.
Save jstejada/98cbb944793b0df3033b to your computer and use it in GitHub Desktop.
tiny lisp interpreter
let env = {
'+': (...args)=> args.reduce((mem, cur)=> mem + cur),
'*': (...args)=> args.reduce((mem, cur)=> mem * cur),
'-': (...args)=> args.reduce((mem, cur)=> mem - cur),
'/': (...args)=> args.reduce((mem, cur)=> mem / cur),
};
function tokenize(expr) {
return expr.replace(/\(|\)/g, ' $& ').trim().split(/\s+/);
}
// TODO
function evaluate(ast) {
return ast || 'Invalid expression';
}
function parse(expr) {
const stack = [];
let curAst = [];
for (const token of tokenize(expr)) {
if (token === '(') {
curAst = [];
stack.push(curAst);
} else if (token === ')') {
const done = stack.pop();
curAst = stack[stack.length - 1] || [];
curAst.push(done);
} else {
curAst.push(token);
}
}
if (stack.length !== 0) return null;
return curAst[0];
}
function main() {
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdout.write('> ');
process.stdin.on('data', (text)=> {
if (text === 'quit\n') {
process.exit();
} else {
console.log(evaluate(parse(text.trim())));
}
process.stdout.write('> ');
});
process.on('exit', ()=> {
console.log('Bye');
});
}
if (require.main === module) {
main();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment