据我了解,标签的使用是定义一个与 flet 相同但具有更高范围的局部函数。那是对的吗。我将提供一个示例:
(defun nested-average (tree)
;labels are the same as flet but with higher scope, define local functions
(labels ((%nested-average
;arguments for the function
(branch sum visited)
(cond
((consp branch)
(multiple-value-call
;calls the previous function with reference to the label
#'%nested-average (rest branch)
(%nested-average (first branch) sum visited)))
;is branch a number
((numberp branch)
(values (+ sum branch) (1+ visited)))
;otherwise
(t
(values sum visited))
)
)
)
(multiple-value-call #'/ (%nested-average tree 0 0))
)
)
;(nested-average ' (10 ((30 1) 20) (8 (5 (50 7)) 9) 40))
来自 Hyperspec:labels 等同于 flet,除了 labels 定义的函数名称的范围包含函数定义本身以及主体。
这实际上意味着标签允许您编写递归函数。例如:
(defun fact (n)
(labels ((rec (x)
(if (< x 1)
1
(* x (rec (- x 1))))))
(rec n)))
这个函数工作正常,但是用flet写的同一个函数会报错,因为函数定义中不会绑定(bind)符号rec。如果您提供的示例函数是用 flet 编写的,出于同样的原因,它会导致错误。
我是一名优秀的程序员,十分优秀!