我有一个称为“联系人”的结构实例的列表,基本上是一个电话号码以及与他们通话的时间。
我现在想将相同电话号码的所有条目与所有通话的总时长相加。
例如:我想转身:
(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))
我使用带有列表缩写的Racket 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))