需要帮助来了解Lisp功能

时间:2020-09-27 21:11:06

标签: recursion lisp common-lisp

我很难理解这个Lisp函数

编写一个函数(使用纯递归技术)以接受嵌套的数字列表 并返回带有负数平方和正数(包括0)的列表 增加2。例如,
LISP> (f '(2 (-1 (9)) 4))

函数结果

(4 (1 (11)) 6)

我不知道如何编写一个返回上面列表的函数

2 个答案:

答案 0 :(得分:4)

将东西平分。例如。

(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)

祝你好运!

答案 1 :(得分:0)

我现在看到的只是@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)