;; Caltech CS1 Fall 2007
;; Scheme code used in Lecture 9 (10/29/07)
;; mvanier@cs.caltech.edu
;; Page 1 of 2

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Data Pairs
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; represent result pairs
(define (make-result x y) (cons x y))
(define (get-x result) (car result))
(define (get-y result) (cdr result))

;; example use
(define a-result (make-result 3 4))
(get-x a-result)
(get-y a-result)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Data Collection 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; sample build
(define my-results
  (list (make-result  1 1.9)
        (make-result  2 4.3)  
        (make-result  3 6.0)))

;; find maximum y value in list of results
(define (find-max-y a-list)
  (define (find-max-y-helper current-list current-y-max)
    (cond ((null? current-list) ;; test for base case
           current-y-max)       ;; handle base case
          ((< (get-y (car current-list)) current-y-max)
           ;; keep old max
           (find-max-y (cdr current-list) current-y-max))
          (else
           ;; new max
           (find-max-y (cdr current-list)  
                       (get-y (car current-list))))))
  (find-max-y-helper a-list 0)) ;; assume y max must be > 0

;; Continued on next page...

                            
;; Page 2 of 2
;; find x value associated with max y
(define (find-x-for-max-y a-list)
    (let ((y-max (find-max-y a-list 0)))
      (find-x-with-y a-list y-max)))

;; find x value associated with target y
;;   (used by above)
(define (find-x-with-y a-list y)
  (cond ((null? a-list)
         (error "No y found to match target y: " y))
        ((= (get-y (car a-list)) y)
         (get-x (car a-list)))
        (else
         (find-x-with-y (cdr a-list) y))))

;; calculating error
(define (calc-error a-list f)
  (if (null? a-list)  
      (list)  ;; empty list; same as "nil"
      (let ((x (get-x (car a-list)))
            (y (get-y (car a-list))))
        (cons (- (f x) y)  ;; build a new list
              (calc-error 
                 (cdr a-list) f)))))

