0

我有一个名为“联系人”的结构的实例列表,它基本上是一个电话号码以及与他们通话的持续时间。

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

例如:我想转:

(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

4

1 回答 1

0

这适用于 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))
于 2020-01-20T02:24:12.063 回答