;;; sample.scm - first Scheme example for CS 313 ;;; ;;; Daniel Scharstein ; This file implements some of the functions discussed in class. To ; run it, start Scheme by typing "scheme" (in this directory). Then ; load this file by typing (load "sample"). This executes all the ; code in this file: ; 1 ]=> (load "sample") ; ; ;Loading "sample.scm" ; ; L = ((a b) ((c)) (d (e))) ; (mylength L) = 3 ; (count-atoms L) = 5 ; (myreverse L) = ((d (e)) ((c)) (a b)) ; (fact 7) = 5040 ; ; -- done ;; handy reload function (define (r) (load "sample")) ;; return length of list x (define (mylength x) (if (null? x) 0 (+ 1 (mylength (cdr x))))) ;; return whether x is an atom (define (atom? x) (not (pair? x))) ;; return number of atoms in x (define (count-atoms x) (cond ((null? x) 0) ((atom? x) 1) (else (+ (count-atoms (car x)) (count-atoms (cdr x)))))) ;; return factorial of n (define (fact n) (if (<= n 1) 1 (* n (fact (- n 1))))) ;; return new list formed by appending x and y (define (myappend x y) (if (null? x) y (cons (car x) (myappend (cdr x) y)))) ;; return reverse of list x (inefficient!) (define (myreverse x) (if (null? x) () (myappend (myreverse (cdr x)) (list (car x))))) ;;; testing: (newline) (newline) (define L '((a b) ((c)) (d (e)))) (display "L = ") (display L) (newline) (display "(mylength L) = ") (display (mylength L)) (newline) (display "(count-atoms L) = ") (display (count-atoms L)) (newline) (display "(myreverse L) = ") (display (myreverse L)) (newline) (display "(fact 7) = ") (display (fact 7)) (newline) (newline) #t ;; to avoid 'unspecified return value' message