Sec*_*coe 2 programming-languages functional-programming metaprogramming common-lisp
我正在寻求为一个简短的演示实现一些概念验证演示,其中正在运行的代码知道当前正在执行的代码块的散列"值".例如:
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;
}
Run Code Online (Sandbox Code Playgroud)
我本能地转向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)
Run Code Online (Sandbox Code Playgroud)
输出:
(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
Run Code Online (Sandbox Code Playgroud)
以下是编写自我重新定义函数的方法:
(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))
Run Code Online (Sandbox Code Playgroud)
顺便提一下,Scheme(以及宏是卫生的任何语言)都会对你产生影响,以防止你创建一个me可以通过传递给宏的源代码引用的标识符.