Art*_*syn 5 common-lisp nested-function
我曾经在Haskell中编写嵌套的辅助函数(其中,顺便说一下,使用外部函数的参数并且是递归的),就像这样(loop):
sum a b = let
loop s i = if i > b then s else loop (s + i) (i + 1)
in loop 0 a
Run Code Online (Sandbox Code Playgroud)
Common Lisp中最清晰的模拟是什么?
我在这里搜索并发现一些讨论集中在从函数返回函数(以及在尝试调用这样的"返回"函数时可能出现的问题),这是不完全相同的情况,据我所知.
标签用于定义本地功能.
CL-USER> (defun thing (x)
(labels ((helper (y) (loop for i from x to y collect i)))
(helper 5)))
THING
CL-USER> (thing 1)
(1 2 3 4 5)
Run Code Online (Sandbox Code Playgroud)
它有点像函数的let*语句,因为您可以定义多个本地函数.所以这里我们有帮助和双重定义.
(defun thing (x)
(labels ((helper (y) (loop for i from x to y collect i))
(double-it (num) (* 2 num)))
(helper (double-it 10))))
Run Code Online (Sandbox Code Playgroud)
你也可以使用lambdas.在这种情况下,这是相当整洁,但在这种情况下我仍然更喜欢标签的可读性.
CL-USER> (defun another-test (x)
(funcall #'(lambda (y) (loop for i from x to y collect i)) 10))
ANOTHER-TEST
CL-USER> (another-test 2)
(2 3 4 5 6 7 8 9 10)
Run Code Online (Sandbox Code Playgroud)
标签也可以递归使用:
CL-USER> (defun test-recurse (x)
(labels ((rec-list (count)
(when (< count x)
(cons count (rec-list (+ 1 count))))))
(rec-list 0)))
TEST-RECURSE
CL-USER> (TEST-RECURSE 10)
(0 1 2 3 4 5 6 7 8 9)
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!