(Setq make-trees 2)
设置变量的值make-trees
为 2,然后返回 2。
在你所描述的内容中我没有看到宏的原因。你的情况是真的吗make-trees
创建一个随机树,它可以被解释为一个程序?只需将其定义为一个函数即可defun
。我在想这样的事情:
(defun make-tree (node-number)
(if (= node-number 1)
(make-leaf)
(cons (get-random-operator)
(mapcar #'make-tree
(random-partition (- node-number 1))))))
Let
and setq
做完全不同的事情。Setq
为现有变量赋值,而let
创建一个带有多个词法绑定的新词法作用域。
我认为你应该展示更多你的代码;目前,你的问题没有多大意义。
Update:
我将修复您的代码片段的缩进以使事情更清晰:
(setq sample
(let* ((trees (make-trees 2))
(tree-bindings (bind-trees trees))
(evaluated-trees (eval-fitness tree-bindings))))
(list (trees tree-bindings evaluated-trees)))
现在,正如之前所写,let*
建立词汇绑定。这些
仅在其主体范围内:
(setq sample
(let* ((trees (make-trees 2))
(tree-bindings (bind-trees trees))
(evaluated-trees (eval-fitness tree-bindings)))
;; here trees, tree-bindings, and evaluated-trees are bound
) ; end of let* body
;; here trees, tree-bindings, and evaluated trees are not in scope anymore
(list (trees tree-bindings evaluated-trees)))
最后一行也是虚假的。如果这些名字被绑定的话
返回一个包含一个元素的列表,这将是评估的结果
功能trees
with tree-bindings
and evaluated-trees
作为
论据。
你可能会得到你想要的东西,如下所示:
(setq sample
(let* ((trees (make-trees 2))
(tree-bindings (bind-trees trees))
(evaluated-trees (eval-fitness tree-bindings)))
(list trees tree-bindings evaluated-trees)))
另一个更新:
宏的目的是在函数无法消除重复代码时消除重复代码。一种常见的应用是在处理位置时,您还需要它们来定义新的控制结构。只要您没有发现某些东西不能作为函数工作,就不要对其使用宏。
以下是一些可能对您有帮助的代码:
(defun make-tree-lambda (depth)
(list 'lambda '(x)
(new-tree depth)))
(defun make-tree-function (lambda-tree)
(eval lambda-tree))
(defun eval-fitness (lambda-form-list input-output-list)
"Determines how well the lambda forms approach the wanted function
by comparing their output with the wanted output in the supplied test
cases. Returns a list of mean quadratic error sums."
(mapcar (lambda (lambda-form)
(let* ((actual-results (mapcar (make-tree-function lambda-form)
(mapcar #'first input-output-list)))
(differences (mapcar #'-
actual-results
(mapcar #'second input-output-list)))
(squared-differences (mapcar #'square
differences)))
(/ (reduce #'+ squared-differences)
(length squared-differences))))
lambda-form-list))
(defun tree-fitness (tree-list input-output-list)
"Creates a list of lists, each inner list is (tree fitness). Input
is a list of trees, and a list of test cases."
(mapcar (lambda (tree fitness)
(list tree fitness))
tree-list
(eval-fitness (mapcar #'make-tree-lambda tree-list)
input-output-list)))