问题描述
我很难理解这个Lisp函数
编写一个函数(使用纯递归技术)以接受嵌套的数字列表 并返回带有负数平方和正数(包括0)的列表 增加2。例如,LISP> (f '(2 (-1 (9)) 4))
函数结果
(4 (1 (11)) 6)
解决方法
将东西平分。例如。
(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)
祝你好运!
,我现在看到的只是@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)