如何在JavaScript中实现lisp的unquote-splice

时间:2018-02-20 09:34:59

标签: javascript macros lisp language-implementation

我有基本的lisp口译员,我正在https://codepen.io/jcubic/pen/gvvzdp?editors=1010

工作

我遇到了非引号拼接和lisp代码的问题:

(print `(,@(list 1 2 3)))

此代码的输出列表结构,来自解析器,如下所示:

(<#symbol 'print'> (<#symbol 'quasiquote'> (<#symbol 'unquote-splicing'> <#symbol 'list'> 1 2 3)))

我的输出为((1 2 3))而不是(1 2 3),我已在biwascheme进行了测试,结果应为(1 2 3)

print函数中的console.log指示它的列表car是哪个(列表1 2 3)而不是列出自己。

我的quasiquote宏看起来像这样:

  quasiquote: new Macro(function(arg) {
    var env = this;
    function recur(pair) {
      if (pair instanceof Pair) {
        if (Symbol.is(pair.car, 'unquote-splicing')) {
          // this if is first invoke of recur function for provided code
          var eval_pair = evaluate(pair.cdr, env);
          if (!eval_pair instanceof Pair) {
            throw new Error('Value of unquote-splicing need to be pair')
          }
          // here eval_pair.car is 1 (first item in list)
          return eval_pair;
        }
        if (Symbol.is(pair.car, 'unquote')) {
          return evaluate(pair.cdr, env);
        }
        var car = pair.car;
        if (car instanceof Pair) {
          car = recur(car);
        }
        var cdr = pair.cdr;
        if (cdr instanceof Pair) {
          cdr = recur(cdr);
        }
        return new Pair(car, cdr);
      }
      return pair;
    }
    return recur(arg);
})

宏只是:

function Macro(fn) {
  this.fn = fn;
}
Macro.prototype.invoke = function(code, env) {
  return this.fn.call(env, code);
};

和我的eval函数看起来像这样:

function evaluate(code, env) {
  env = env || global_env;
  var value;
  if (typeof code === 'undefined') {
    return;
  }
  var first = code.car;
  if (first instanceof Symbol) {
    var rest = code.cdr;
    // resolve return value from environment
    value = resolve(first, env);
    if (value instanceof Macro) {
      return value.invoke(rest, env);
    } else if (typeof value !== 'function') {
      throw new Error('Unknown function `' + first.name + '\'');
    } else {
      var args = [];
      var node = rest;
      while(true) {
        if (node !== nil) {
          args.push(evaluate(node.car, env));
        }
        if (node.cdr === nil) {
          break;
        }
        node = node.cdr;
      }
      return value.apply(env, args);
    }
  } else if (code instanceof Symbol) {
    value = resolve(code, env);
    if (value === 'undefined') {
      throw new Error('Unbound variable `' + code.name + '\'');
    }
    return value;
  } else {
    return code;
  }
}

0 个答案:

没有答案