; len computes the length of its argument list (only top level ; elements are counted, so len is a "shallow" function i.e. it ; doesn't splice into sublists. For example (len '(1 (2 (3)) 5)) = 3. (define (len x) (cond ((null? x) 0) (else (+ 1 (len (cdr x)))))) ; atomcount counts the number of atoms in its arg. This is an example ; of a "deep" function which goes inside the sublists to count the no. ; of atoms. For example (atomcount '(1 (2 (3)) 5)) = 4. ; We need to define the auxiliary function atom? which checks if its ; arg is an atom (i.e. a symbol or a number). (define (atom? object) (not (pair? object))) (define (atomcount x) (cond ((null? x) 0) ; () has 0 atoms ((atom? x) 1) ; if the arg is an atom return 1 (else (+ (atomcount (car x)) (atomcount (cdr x)))))) ; recursive case (arg is a list). ; return atomcount in its car plus atomcount ; in its cdr ; app returns a list which is formed by concatenating its 2 list args. ; this is like append in prolog ; e.g. (app '(1 2) '(3)) = '(1 2 3), (app '(1 (2)) '((4))) = '(1 (2) (4)) (define (app x y) (cond ((null? x) y) ; if one of the lists is empty, the result ((null? y) x) ; will be the second list. (else (cons (car x) (app (cdr x) y))))) ; recursive case (both lists are nonempty)