【发布时间】:2021-01-13 12:22:39
【问题描述】:
我无法理解这个 lisp 函数
编写一个接受嵌套数字列表的函数(使用纯递归技术) 并返回负数平方和正数(包括0)的列表 增加 2。例如,LISP> (f '(2 (-1 (9)) 4))函数的结果
(4 (1 (11)) 6)
我不知道如何编写一个返回类似上述列表的函数
【问题讨论】:
标签: recursion lisp common-lisp
我无法理解这个 lisp 函数
编写一个接受嵌套数字列表的函数(使用纯递归技术) 并返回负数平方和正数(包括0)的列表 增加 2。例如,LISP> (f '(2 (-1 (9)) 4))函数的结果
(4 (1 (11)) 6)
我不知道如何编写一个返回类似上述列表的函数
【问题讨论】:
标签: recursion lisp common-lisp
我现在看到这只是@Sylwester 答案的尾递归版本。
将负数平方并在正数上加 2:
(defun procedure (x) (if (< 0 x) (+ 2 x) (* x x)))
通过编写递归函数
(defun apply-to-every (fun l &optional (acc '()))
(cond ((null l) (nreverse acc))
((atom (car l))
(apply-to-every fun
(cdr l)
(cons (funcall fun (car l))
acc)))
(t ;; if not an atom it must be a list
(apply-to-every fun
(cdr l)
(cons (apply-to-every fun (car l))
acc)))))
然后应用它:
(apply-to-every #'procedure '(2 (-1 (9)) 4))
;; (4 (1 (11)) 6)
;; or:
(defun f (list)
(apply-to-nested-list #'procedure list))
(f '(2 (-1 (9)) 4))
;; (4 (1 (11)) 6)
【讨论】:
(defun map-nested (fun l) (mapcar #'(lambda (a) (if (atom a) (funcall fun a) (map-nested fun a))) l))。 :)
mapcar* ;) - 是的,它是嵌套列表中的mapcar ...
把东西分开。例如。
(defun process (n)
(if (< n 0)
...
...))
(process -2) ; ==> 4
(process 4) ; ==> 6
那么你需要让函数本身来迭代一棵树。
(defun process-tree (tree)
(cond ((numberp tree) (process tree)) ; the processing of value happens here
((consp tree) ???) ; the recursion happens here
(t tree))) ; any values inside the tree not numbers. eg. ()
(process-tree -2) ; ==> 4
(process-tree 4) ; ==> 6
(process-tree '()) ; ==> ()
(process-tree 'test) ; ==> test (out of spec, a feature)
(process-tree '(-2 . 4)) ; ==> (4 . 6)
(process-tree '(2 (-1 (9)) 4))) ; ==> (4 (1 (11)) 6)
祝你好运!
【讨论】: