;; ****************** ;; Assignment 8 Q3 ;; Mark Leung ;; 20266764 ;; ****************** ;; ********* ;; 3A) ;; ********* ;; Contract: foldr2: (X X -> Y) (Listof X) (Listof X)=> (Listof Y) ;; Purpose: Applies a function on both elements of a list. ;; Examples: (foldr2 + 0 '(1 2 3) '(4 5 6 7)) => 21 ;; (foldr2 * 1 '(1 2 3) '(3 2 1)) => 36 ;; Definitions: (define (foldr2 f base list1 list2) (cond [(and (empty? list1) (empty? list2)) base ] [(and (empty? list1) (cons? list2)) (f (first list2) (foldr2 f base empty (rest list2))) ] [(and (empty? list2) (cons? list1)) (f (first list1) (foldr2 f base (rest list1) empty)) ] [ else (f (first list1) (first list2) (foldr2 f base (rest list1) (rest list2))) ] )) ;; Tests: " Tests foldr2" ( = (foldr2 + 0 '(1 2 3) '(4 5 6 7)) 28) ( = (foldr2 * 1 '(1 2 3) '(3 2 1)) 36) ( = (foldr2 + 0 '(1 2 3) '(1 1 1 1 1)) 11) ;; ************ ;; 3B) ;; ************ ;; Contract: map2: (X -> Y) (Listof X) (Listof X) => (Listof Y) ;; Purpose: Makes a list of the result of function foldr2 on each element of list. ;; Examples: (map2 + '(1 2 3) '(1 2 3)) => '(2 4 6) ;; (map2 + '(1 1 1) '(1 1 1)) => '(2 2 2) ;; Definitions: (define (map2 f list1 list2) (foldr2 (lambda (a b c) (cons (f a b) c)) empty list1 list2)) ;; Tests: "Tests map2" (equal? (map2 + '(1 2 3) '(1 2 3)) '(2 4 6)) (equal? (map2 + '(1 1 1) '(1 1 1)) '(2 2 2)) ;; ************* ;; ********* ;; 3C) ;; ********* ;; Contract: zip: (listof X) (listof X) => (listof Y) ;; Purpose: Returns a lists of two-element lists, from corresponding elements in the two original lists ;; Examples: (zip '(a b c d) '(1 2 3 4)) => (list (list 'a 1) (list 'b 2) (list 'c 3) (list 'd 4)) ;; (zip '(1 2 3 4) '(a b c d)) => (list (list 1 'a) (list 2 'b) (list 3 'c) (list 4 'd)) ;; Definitions: (define (zip list1 list2) (foldr2 (lambda (a b c) (cons (list a b) c)) empty list1 list2)) ;; Tests: " Tests zip function" (equal? (zip '(a b c d) '(1 2 3 4)) (list (list 'a 1) (list 'b 2) (list 'c 3) (list 'd 4))) (equal? (zip '(1 2 3 4) '(a b c d)) (list (list 1 'a) (list 2 'b) (list 3 'c) (list 4 'd))) ;; ******** ;; 3D) ;; ******** ;; Contract: dot-product: alon alon => num ;; Purpose: Gets the dot product of the two lists. ;; Examples: (dot-product '(2 3 4) '(4 3 1)) => 21 ;; (dot-product '(1 2 3) '(3 2 1)) => 10 ;; (dot-product '(1 1 1) '(2 2 2)) => 6 ;; Definitions: (define (dot-product alon1 alon2) (foldr2 (lambda (a b c) (+ ( * a b) c)) 0 alon1 alon2)) ;; Tests: "Tests dot-product function" ( = (dot-product '(2 3 4) '(4 3 1)) 21) ( = (dot-product '(1 2 3) '(3 2 1)) 10) ( = (dot-product '(1 1 1) '(2 2 2)) 6) ;; -------------- ;; ********************* ;; PROGRAM FINISHED ;; *********************