;; The 3 functions defined here illustrate 3 different situations that ;; might arise when creating the template for a function that consumes ;; two or more classes of union data (i.e., data defined using an "or"), ;; which includes those classes of data defined by self-referential data ;; definitions like the List-of-Numbers data used here. ;; Data definition: ;; ;; A List-of-Numbers is one of ;; - empty ;; - (cons Number List-of-Numbers) ;; 1. An example where the template is dictated by only one of the inputs: ;; ;; my-append : List-of-Numbers List-of-Numbers -> List-of-Numbers ;; appends two lists of numbers (without using Scheme's append function) (define (my-append l1 l2) (cond [(empty? l1) l2] [(cons? l1) (cons (first l1) (my-append (rest l1) l2))])) ;; Example and test of my-append (equal? (my-append (list 1 2 3 4) (list 9 8 7)) (list 1 2 3 4 9 8 7)) ;; 2. An example when inputs are handled according to "parallel form": ;; This is another situation when the template is determined by only ;; one of the inputs (but it could be any one). ;; ;; add-corresp1 : List-of-Numbers List-of-Numbers -> List-of-Numbers ;; produces a list containing the sum of corresponding numbers in the two ;; lists; assumes the two lists are the same length (define (add-corresp1 l1 l2) (cond [(empty? l1) empty] [(cons? l1) (cons (+ (first l1) (first l2)) (add-corresp1 (rest l1) (rest l2)))])) ;; Example and test of add-corresp1 (equal? (add-corresp1 (list 1 2 3 4) (list 6 7 8 9)) (list 7 9 11 13)) ;; 3. An example in which all combinations must be considered: ;; ;; add-corresp2 : List-of-Numbers List-of-Numbers -> List-of-Numbers ;; produces a list containing the sum of corresponding numbers in the two ;; lists; the shorter list is treated as if it were filled with extra zeros (define (add-corresp2 l1 l2) (cond [(and (empty? l1) (empty? l2)) empty] [(and (empty? l1) (cons? l2)) l2] [(and (cons? l1) (empty? l2)) l1] [(and (cons? l1) (cons? l2)) (cons (+ (first l1) (first l2)) (add-corresp2 (rest l1) (rest l2)))])) ;; Examples and tests of add-corresp2 (equal? (add-corresp2 (list 1 2 3 4) (list 6 7 8 9)) (list 7 9 11 13)) (equal? (add-corresp2 (list 1 2 3) (list 6 7 8 9)) (list 7 9 11 9)) (equal? (add-corresp2 (list 1 2 3 4) (list 6)) (list 7 2 3 4))