球拍 BSL:如何在列表中组合具有一个共同属性的两个结构实例?



我有一个名为"contact"的结构的实例列表,它基本上是一个电话号码和与他们通话的持续时间。

我现在想将同一电话号码的所有条目与与他们的所有通话的总持续时间相加。

例如:我想转:

(list
(make-contact "0111222222" 2)
(make-contact "0111222222" 6)
(make-contact "0111333333" 5)
(make-contact "0111444444" 3)
(make-contact "0111555555" 8)
(make-contact "0111555555" 2))

到:

(list
(make-contact "0111222222" 8)
(make-contact "0111333333" 5)
(make-contact "0111444444" 3)
(make-contact "0111555555" 10))

我使用带有列表缩写的球拍 BSL

这适用于 htdp/bsl(我很好奇是否有更干净的解决方案(:

#lang htdp/bsl
(define-struct contact (number time))
(define contacts (list
(make-contact "0111222222" 2)
(make-contact "0111222222" 6)
(make-contact "0111333333" 5)
(make-contact "0111444444" 3)
(make-contact "0111555555" 8)
(make-contact "0111555555" 2)))
(define (sum-contacts acc s)
(cond [(empty? s) acc]
[(and (not (empty? acc))
(equal? (contact-number (first s))
(contact-number (first acc))))
(sum-contacts (cons
(make-contact
(contact-number (first s))
(+ (contact-time (first s))
(contact-time (first acc)))) (rest acc))
(rest s))]
[else (sum-contacts (cons (first s) acc) (rest s))]))
(reverse (sum-contacts '() contacts))