;; An Atom is one of: ;; - Number ;; - Symbol ;; - String ;; atom? : Anything -> Boolean ;; is the input a atom? (define (atom? a) (or (number? a) (symbol? a) (string? a))) ;; atom=? : Atom Atom -> Boolean ;; are the two atoms equal? (define (atom=? a1 a2) (cond [(number? a1) (and (number? a2) (= a1 a2))] [(symbol? a1) (and (symbol? a2) (symbol=? a1 a2))] [(string? a1) (and (string? a2) (string=? a1 a2))])) (check-expect (atom=? 3 'foo) false) (check-expect (atom=? 3 3) true) ;;;;;;;;;;;;;;;;;;;; ;; An SExp is one of: ;; - Atom ;; - LOS ;; An LOS (listof SExp) is one of: ;; - empty ;; - (cons SExp LOS) ;; Examples (SExp) 3 'red "yellow" empty (define sexp1 (list "banana" 27 'grapefruit)) (define sexp2 (list (list 'red 'yellow (list "banana" 27 'grapefruit)) (list 1 2) "foo")) ;; atom-occurs? : SExp Atom -> Boolean ;; does the atom occur anywhere in the given sexp? (define (atom-occurs? s a) (cond [(atom? s) (atom=? s a)] [else (los-atom-occurs? s a)])) ;; los-atom-occurs? : LOS Atom -> Boolean ;; does the atom occur in los? (define (los-atom-occurs? los a) (cond [(empty? los) false] [(cons? los) (or (atom-occurs? (first los) a) (los-atom-occurs? (rest los) a))])) ;; template for SExp #;(define (sexp-temp s) (cond [(atom? s) ...] [else ... (los-temp s) ...])) ;; template for LOS #;(define (los-temp los) (cond [(empty? los) ...] [(cons? los) ... (sexp-temp (first los)) ... (los-temp (rest los))])) (check-expect (atom-occurs? sexp2 "banana") true) (check-expect (atom-occurs? 5 "banana") false) (check-expect (atom-occurs? sexp1 'yellow) false) (check-expect (atom-occurs? empty "banana") false) ;; flatten : SExp -> SExp ;; flatten the given sexpr (see examples) (define (flatten s) (cond [(atom? s) s] [else (los-flatten s)])) ;; los-flatten : LOS -> LOS (define (los-flatten los) (cond [(empty? los) ...] [(cons? los) ... (flatten (first los)) ... (los-flatten (rest los))])) (check-expect (flatten 4) 4) (check-expect (flatten empty) empty) (check-expect (flatten sexp1) sexp1) (check-expect (flatten sexp2) (list 'red 'yellow "banana" 27 'grapefruit 1 2 "foo"))