Last active
October 13, 2015 21:12
-
-
Save jstejada/98cbb944793b0df3033b to your computer and use it in GitHub Desktop.
tiny lisp interpreter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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