#lang racket ;; Mini Exercise 3 Solution ;; 1. Version of my-or that avoids an extra "if" (define-syntax my-or (syntax-rules () ((my-or) #f) ((my-or e) e) ((my-or e1 e2 ...) (let ((temp e1)) (if temp temp (my-or e2 ...)))))) ;; 2. my-if using delay and force (define (my-if a b c) (if a (force b) (force c))) ;; sample call: (my-if (= 1 1) (delay (+ 2 4)) (delay (/ 10 0))) ;; 5. '( ( 1 . 2) (3 . 4)) ;; 6. my-max. We will use Racket's syntax for gathering an indefinite ;; number of arguments - but we require at least 1 (define (my-max x . xs) (my-max-helper x xs)) ;; my-max-helper takes a biggest element (so far) and a list, and finds the maximum ;; of biggest and the elements in rest (define (my-max-helper biggest rest) (cond ((null? rest) biggest) ((> (car rest) biggest) (my-max-helper (car rest) (cdr rest))) (else (my-max-helper biggest (cdr rest))))) ;; alternative version of my-max that doesn't use a helper function. We ;; use 'apply' to get around the fact that on the recursive call we've got ;; the arguments in a list already (define (my-max2 x . xs) (cond ((null? xs) x) ((> (car xs) x) (apply my-max2 xs)) (else (apply my-max2 (cons x (cdr xs)))))) ;; yet another version, which checks that there is at least 1 argument in ;; the function rather than in the argument list (define (my-max3 . xs) (cond ((null? xs) (error "my-max3 needs at least one argument")) ((null? (cdr xs)) (car xs)) ((> (car xs) (cadr xs)) (apply my-max3 (cons (car xs) (cddr xs)))) (else (apply my-max3 (cdr xs)))))