【问题标题】:Need help understanding lisp function需要帮助理解 lisp 函数
【发布时间】:2021-01-13 12:22:39
【问题描述】:

我无法理解这个 lisp 函数

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

函数的结果

(4 (1 (11)) 6)

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

【问题讨论】:

    标签: recursion lisp common-lisp


    【解决方案1】:

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

    【讨论】:

    • 我也这么认为,但文字说它是负数的平方。不好的示例数据。 :)
    • @WillNess 谢谢 xD - 是的,选择不愉快的例子。
    • 实际上,它正在重新实现 mapcar(defun map-nested (fun l) (mapcar #'(lambda (a) (if (atom a) (funcall fun a) (map-nested fun a))) l))。 :)
    • 你的意思是mapcar* ;) - 是的,它是嵌套列表中的mapcar ...
    【解决方案2】:

    把东西分开。例如。

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

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 2019-08-11
      相关资源
      最近更新 更多