本文介绍了Racket BSL:如何在具有一个共同属性的列表中组合结构的两个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为contact"的结构实例列表,它基本上是一个电话号码以及与他们通话的持续时间.
I have a list of instances of a structure called "contact", which is basically a phone number and the duration a call with them took.
我现在想将同一电话号码的所有条目与所有通话的总时长加在一起.
I now want to add together all entries of the same phone number with the total duration of all calls with them.
例如:我想转:
(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
Im using Racket BSL with List abbreviations
推荐答案
这适用于 htdp/bsl(我很好奇是否有更简洁的解决方案):
This works with htdp/bsl (i'm curious if there is a cleaner solution):
#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))
这篇关于Racket BSL:如何在具有一个共同属性的列表中组合结构的两个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!