0

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.

E.g: i want to turn:

(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))

into:

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

Im using Racket BSL with List abbreviations

soegaard
  • 30,661
  • 4
  • 57
  • 106
Another Noone
  • 11
  • 1
  • 5

1 Answers1

0

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))
vonschlager
  • 324
  • 1
  • 6