; abs : num -> num << CONTRACT ; Takes n and returns |n| << DESCRIPTION ; (abs 5) = 5 << EXAMPLES ; (ans -5) = 5 ; (abs 0) = 0 (define (abs n) (if (< n 0) (- n) n)) ; flip : pair -> pair ; ... ; (flip '(a . b)) = _(b . a)_ ; (flip '(0 . w)) = _(w . 0)_ (define (flip p) (cons (cdr p) (car p))) ; sum-pair : numpair -> num ; (sum-pair '(a . b)) = <<<<< don't need, according ; to the contract ; (sum-pair '(1 . 2)) = 3 (define (sum-pair p) (+ (car p) (cdr p) )) ; A numpair is ; (cons n1 n2) ; where n1, n2 are nums ; A glomph is ; (cons g1 g2) ; where g1,g2 are glomphs ; glomph is NONSENSE, because we can't create any ; instances of the datatype ; A blim is either ; * 0 ; * (cons 1 b) ; where b is a blim ; Example blims: ; 0 ; (cons 1 0) ; (cons 1 (cons 1 (cons 1 (cons 1 0)))) ; add-blim : blim -> num ; Sums all 1s in b ; (add-blim (cons 1 0)) = 1 ; (add-blim 0) = 0 (define (add-blim b) (cond [(and (number? b) (zero? b)) 0] [(pair? b) (+ (car b) (add-blim (cdr b))) ])) ; NOTE that the function definition parallels the ; data definition. ; A bitseq is either ; * '() ; * (cons 0 b) ; * (cons 1 b) ; where b is a bitseq ; Examples: ; '() ; (cons 0 '()) = '(0) ; '(1 1 0 1 1 0 1) = (list 1 1 0 1 1 0 1) ; parity : bitseq -> num ; Returns 0 if b has an even number of 1s, ; 1 otherwise ; (parity '()) = 0 ; (parity '(1 1 0 1 1 0 1)) = 1 (define (parity b) (cond [(null? b) 0] [(zero? (car b)) (parity (cdr b)) ] [(= (car b) 1) (if (= (parity (cdr b)) 1) 0 1)])) ; REVISED DATA DEFN: ; A bitseq is either ; * '() ; * (cons 0 b) ; * (cons 1 b) ; * (cons 2 b) ; * (cons 3 b) ; where b is a bitseq ; New examples: ; '(3 2 0 1) ; REVISE parity ; parity : bitseq -> num ; Returns 0 if b has an even number of non-zeros, ; 1 otherwise ; (parity '()) = 0 ; (parity '(1 1 0 1 1 0 1)) = 1 ; (parity '(3 2 0 1)) = 1 (define (parity b) (cond [(null? b) 0] [(zero? (car b)) (parity (cdr b)) ] [(= (car b) 1) (if (= (parity (cdr b)) 1) 0 1)] [(= (car b) 2) ...] ;; <<< ONLY NEW PARTS [(= (car b) 3) ...])) ;; <<< ; BNF Backus-Naur Form ; = () ; | (0 . ) ; | (1 . ) ; | (2 . ) ; | (3 . ) ; (1 2 3) = (1 . (2 . (3 . ()))) ; = () ; | ( . ) ; = ; | ; Examples: ; _(x)_ = _(x . ())_ ; _(lambda (x) x)_ = _(lambda . ((x) x))_ ; = _(lambda . ((x) . (x)))_ ; contains-apple? : s-list -> bool ; Returns #t is sl contains 'apple ; #f otherwise ; (contains-apple? '(apple)) = #t ; (contains-apple? '()) = #f (define (contains-apple? sl) (cond [(null? sl) #f] [else (or (contains-apple/sexp? (car sl)) (contains-apple? (cdr sl))) ])) (define (contains-apple/sexp? se) (cond [(symbol? se) (eq? se 'apple)] [else (contains-apple? se) ])) ; so, mutually-recursive datatypes produce ; mutaually-recursive functions