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

问题描述 投票:0回答:1

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

我现在想将相同电话号码的所有条目与所有通话的总时长相加。

例如:我想转身:

(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

racket racket-student-languages
1个回答
0
投票
#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))
© www.soinside.com 2019 - 2024. All rights reserved.