Advertisement
Guest User

Untitled

a guest
Feb 12th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. // ramda 0.17.1
  2.  
  3. import {
  4. pipe, replace, split, curry, append,
  5. head, tail, nth, length, map, zipObj,
  6. values, merge, isArrayLike, apply, filter} from 'ramda'
  7. import fs from 'fs'
  8.  
  9. const tokenize = pipe(replace(/\(/g, '( '), replace(/\)/g, ' )'), split(/\s+/))
  10.  
  11. const ast = curry((list, tokens) => {
  12. if (length(tokens) == 0) {
  13. return list
  14. }
  15. if (head(tokens) == '(') {
  16. const x = ast([], tail(tokens))
  17. return ast(append(nth(0, x), list), nth(1, x))
  18. }
  19. if (head(tokens) == ')') {
  20. return [list, tail(tokens)]
  21. }
  22. return ast(append(head(tokens), list), tail(tokens))
  23. })
  24.  
  25. const parse = pipe(tokenize, ast([]))
  26.  
  27. const evaluate = curry((env, x) => {
  28. if (!isArrayLike(x)) {
  29. return env[x]
  30. }
  31. if (x[0] === 'def') {
  32. const [, name, exp] = x
  33. env[name] = evaluate(env, exp)
  34. return
  35. }
  36. if (x[0] === '#') {
  37. const [, params, body] = x
  38. return function() {
  39. const localEnv = merge(env, zipObj(params, values(arguments)))
  40. return evaluate(localEnv, body)
  41. }
  42. }
  43. const [name, ...rest] = x
  44. return apply(evaluate(env, name), map(evaluate(env), rest))
  45. })
  46.  
  47. const env = {}
  48. const program = fs.readFileSync('program.la', 'utf8')
  49.  
  50. const result = pipe(parse, map(evaluate(env)))(program)
  51.  
  52. console.log(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement