Thursday, 15 September 2011

Exercise 144 - Phone Numbers

Exercise 144: Here is one way to represent a phone number:

    (define-struct phone (area switch four))
    ; An Phone is a structure:
    ; (make-addr Three Four)
    ; A Three is between 100 and 999.
    ; A Four is between 1000 and 9999. 

Design the function replace. It consumes a list of Phones and produces one.
It replaces all area codes 713 with 281.



The question itself doesn't seem to make sense (at least to me). make-addr is not defined. Is it
meant to be area? Why does it define Three and Four and use switch and four in the
struct...  I think this stuff is probably irrelevant for the question though...

(require racket/base)
(define-struct phone (area switch four))
(define OLD_CODE 713)
(define NEW_CODE 281)


; replaces a section of a struct within a list of phone numbers
(define (replace alop) 
  (cond ((empty? alop) empty)
        ((cons? alop) (cons (helper (first alop)) 
                            (replace (rest alop))))))




(define (helper phone)
  (make-phone
   (substitute (phone-area phone))
   (phone-switch phone)
   (phone-four phone)))


; swaps the area codes if they match
(define (substitute area)
  (cond ((= area OLD_CODE) NEW_CODE)
        (else area)))


; this test is failing, but a visual eyeball of the results show that 
; expected and actual results are identical - not sure if it's some weirdness
; to do with comparing structs.... but not going to waste too much time trying
; to track down whats up...
(check-expect (replace (list (make-phone 123 456 789)
                             (make-phone 713 456 8753)
                             (make-phone 281 432 234)))
              (list (make-phone 123 456 789)
                             (make-phone 281 456 8753)
                             (make-phone 281 432 234)))
                     

;

No comments:

Post a Comment