Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ramda 0.17.1
- import {
- pipe, replace, split, curry, append,
- head, tail, nth, length, map, zipObj,
- values, merge, isArrayLike, apply, filter} from 'ramda'
- import fs from 'fs'
- const tokenize = pipe(replace(/\(/g, '( '), replace(/\)/g, ' )'), split(/\s+/))
- const ast = curry((list, tokens) => {
- if (length(tokens) == 0) {
- return list
- }
- if (head(tokens) == '(') {
- const x = ast([], tail(tokens))
- return ast(append(nth(0, x), list), nth(1, x))
- }
- if (head(tokens) == ')') {
- return [list, tail(tokens)]
- }
- return ast(append(head(tokens), list), tail(tokens))
- })
- const parse = pipe(tokenize, ast([]))
- const evaluate = curry((env, x) => {
- if (!isArrayLike(x)) {
- return env[x]
- }
- if (x[0] === 'def') {
- const [, name, exp] = x
- env[name] = evaluate(env, exp)
- return
- }
- if (x[0] === '#') {
- const [, params, body] = x
- return function() {
- const localEnv = merge(env, zipObj(params, values(arguments)))
- return evaluate(localEnv, body)
- }
- }
- const [name, ...rest] = x
- return apply(evaluate(env, name), map(evaluate(env), rest))
- })
- const env = {}
- const program = fs.readFileSync('program.la', 'utf8')
- const result = pipe(parse, map(evaluate(env)))(program)
- console.log(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement