gpt4 book ai didi

list - 如何在 lisp 中使用标签需要帮助

转载 作者:太空宇宙 更新时间:2023-11-03 18:48:18 24 4
gpt4 key购买 nike

据我了解,标签的使用是定义一个与 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 编写的,出于同样的原因,它会导致错误。

关于list - 如何在 lisp 中使用标签需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13252376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com