我正在寻找一个简短演示的概念验证演示,其中正在运行的代码了解当前正在执行的代码块的哈希“值”。例如:

function BBB(a) {
  a = 2 * a;
  print me.hash;          --> "xxxxxxx" (value of BBB-syntax represenation)
  return a;
}

function AAA(a, b, c) {
  d = BBB(a);
  print me.hash;          --> "yyyyyyy" (value of AAA-Syntax representation, possibly dependant on value of BBB, but not necessary)
  return d;
}


我本能地转向LISPish语言,但使用Scheme仍未成功。而且我已经很长时间没有与Common LISP保持联系了,我怀疑这可能能够做到(感谢提示)。它不一定要快,也不是流行的平台,可以是最学术,最怪异的平台。这只是一个演示。

是否有人知道一种语言/平台,可以在开箱即用的情况下进行相当多的操作,或者几乎不需要动手就能做到?我更喜欢使用某种解析/树式的东西,而不是实际的源代码。

最佳答案

你猜到了。 Common Lisp可以很容易地做到这一点:

(defmacro reflective-defun (name args &body body)
  (let ((source-form `(reflective-defun ,name ,args ,@body)))
    `(let ((me ',source-form))
       (defun ,@(cdr source-form)))))

(reflective-defun bbb (a)
  (setf a (* 2 a))
  (print me)
  a)

(reflective-defun aaa (a b c)
  (let ((d (bbb a)))
    (print me)
    d))

(aaa 12 :x :y)


输出:

(REFLECTIVE-DEFUN BBB
    (A)
  (SETF A (* 2 A))
  (PRINT ME)
  A)
(REFLECTIVE-DEFUN AAA
    (A B C)
  (LET ((D (BBB A)))
    (PRINT ME)
    D))
24


这是编写自定义函数的方法:

(defun recursive-replace (tree what with)
  "Walks down the TREE and replaces anything that is EQUALP to WHAT with WITH."
  (cond ((equalp tree what)
         with)
        ((listp tree)
         (loop for item in tree
              collect (recursive-replace item what with)))
        (t tree)))

(reflective-defun ccc (a b c)
  (let ((d (bbb a)))
    (print me)
    (if (eql b :use-me-from-now-on)
        (eval (recursive-replace me '(bbb a) '(bbb b))))
    d))


顺便说一句,Scheme(以及宏是卫生的任何语言)都会使您费劲,以防止您创建名为me的标识符,该标识符可由传递给宏的源代码引用。

10-08 04:04