Functional programming 如何在Scheme/Lisp中编写此数据结构的平均函数?

Functional programming 如何在Scheme/Lisp中编写此数据结构的平均函数?,functional-programming,lisp,scheme,racket,Functional Programming,Lisp,Scheme,Racket,我想根据类似商品的平均价格来计算新商品的价格。 函数get-k-similor使用k-最近邻,但返回此输出 ((列出评级年限价格)接近度) 我需要找到类似物品的平均价格。i、 e平均数为117和75。 有更好的迭代方法吗?我的功能看起来太难看了 (define (get-prices new-item) (define (average-prices a-list) (/ (cdr (foldl (λ(x y) (cons (list 0 0 0)

我想根据类似商品的平均价格来计算新商品的价格。 函数get-k-similor使用k-最近邻,但返回此输出
((列出评级年限价格)接近度)

我需要找到类似物品的平均价格。i、 e平均数为117和75。 有更好的迭代方法吗?我的功能看起来太难看了

(define (get-prices new-item)

  (define (average-prices a-list)
    (/ (cdr 
        (foldl (λ(x y) (cons (list 0 0 0)
                             (+ (third (car x)) (third (car y))))) 
               (cons (list 0 0 0) 0)
               a-list))
        (length a-list)))

    (let ((similar-items (get-k-similar new-item)))
      (average-prices similar-items)))
公共口齿不清

(/ (reduce '+ a-list :key 'caddar) (length a-list))


您可以做一件简单的事情,只需拉出每三个值:

(define (average-prices a-list)
  (/ (apply + (map fourth a-list)) (length a-list)))
这有点低效,因为它构建了一个中间列表,我猜这就是您尝试
foldl
的原因。下面是正确的方法:

(define (average-prices a-list)
  (/ (foldl (lambda (x acc) (+ (third x) acc)) 0 l)
     (length a-list)))

还有一点效率低下--
length
正在进行第二次扫描--但这是您不应该担心的事情,因为您需要一些非常长的列表来获得任何明显的减速。

您提出了一个有趣的观点。我可以在添加项目时累加列表的长度吗?当然可以,有几种方式,包括命令式和功能性。但是在这个阶段,如果我是你的话,我就不会为此烦恼了。我冒昧地对你的代码进行了适当的缩进。我无法想象这会产生任何有意义的结果。
(define (average-prices a-list)
  (/ (apply + (map fourth a-list)) (length a-list)))
(define (average-prices a-list)
  (/ (foldl (lambda (x acc) (+ (third x) acc)) 0 l)
     (length a-list)))