嵌套列表平均值

时间:2012-11-03 19:05:25

标签: list lisp

大家好我已经实现了一个解决方案来查找嵌套列表的平均值。所以我想知道你是否能想到一个更好的解决方案或任何可能的错误与我的欢呼。

; takes a nested list and return a flattened list
(defun flatten-list (list)
  (cond 
     ((null list) list)  
     ((atom list) (list list))  
     ((list (first list))
            (append (flatten-list (first list))
                    (flatten-list (rest  list)))) 

   (t      
            (append (list (first list))
                          (flatten-list (rest  list))))
   ))

;takes a flattened list and return the sum of the numbers
(defun sum-list (list)
  (cond ((null list)
         0)    
        (t
         (+ (first list) (sum-list(rest list))))
        ))

;uses the flatten-list and nested-average to find the average
(defun nested-average (list)  
  (sum-list  (flatten-list list))
  (defvar flat-lis)
  (setf flat-list (flatten-list list))
  (/ (sum-list  flat-list) (length flat-list)
  ))

2 个答案:

答案 0 :(得分:1)

第一个函数包含无法访问的代码。永远不会使用该代码。文档字符串也是错误的,因为它并没有真正描述函数的功能。

使用REDUCE更好地编写第二个函数。

需要重写第三个功能。不使用第一个表单的值。使用DEFVARSETF是错误的。

答案 1 :(得分:1)

我认为这是更好的解决方案......

(defun tree-average (tree)
  (labels ((%tree-average
            (branch sum visited)
            (cond
             ((consp branch)
              (multiple-value-call
               #'%tree-average (cdr branch)
               (%tree-average (car branch) sum visited)))
             ((numberp branch)
              (values (+ sum branch) (1+ visited)))
             (t (values sum visited)))))
    (multiple-value-call #'/ (%tree-average tree 0 0))))

好吧,如果你问。