0

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

; 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)
  ))
4

2 回答 2

1

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

第二个函数最好用REDUCE.

第三个函数需要重写。不使用第一种形式的值。使用DEFVARandSETF是错误的。

于 2012-11-03T19:27:39.753 回答
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))))

好吧,如果你问。

于 2012-11-04T09:36:24.357 回答