Some Scheme examples

(display "testing null?")
(null? '())
(null? '(3 7))
(null? 8)

(display "testing a conditional")
(define x (cond ((> 1 2) 6) (#f 5)))
x ;x is undefined
(define y (cond (#f 5) (#t 6)))
y

(display "a recursive definition of power")
(define power (lambda (x n) (cond ((eq? n 0) 1)
                ((> n 0) (* x (power x (- n 1)))))))
(power 2 8)
(power 8 2)

(display "testing pair?")
(define x 5)
(define y 7)
(or (pair? x)  (not (pair? y)))

(display "a template for constructing functions:")
(define add-template (lambda (x) (lambda (y) (+ x y))))
(define add3 (add-template 3))
(add3 5)
(define add5 (add-template 5))
(add5 6)

(display "a template that takes another function as a parameter:")
(define choose-template (lambda (x) (lambda (y z) 
                                      (cond ((x y z) y)
                                            (#t z)))))
(define mymin (choose-template <))
(mymin 3 4)
(mymin 5 7)
(define less-sq (choose-template (lambda (x y) (< x (* y y)))))
(less-sq 20 5)
(less-sq 26 5)  

(display "manipulating scheme expressions at run-time:")
; pre-add5 is a non-evaluated expression for a function 
; that adds 5 to a number
(define pre-add5 '(lambda (x) (+ x 5)))
; before we apply it, we need to evaluate it
((eval pre-add5) 7)
; changing pre-add5 to pre-add6
(define pre-add6 (letrec  ((subst (lambda (x) 
                             (cond ((pair? x) (cons (subst (car x)) 
                                                    (subst (cdr x))))
                                   (#t (cond ((eq? x 5) 6) (#t x)))))))
                (subst pre-add5)))
((eval pre-add6) 6)

(display "set! statement test:")
;imerative features in Scheme
(define n 7)
(set! n #t)
n
(define z (cons x y))
(set-car! z 5)
(set-cdr! z "apple")
z
x
y

This is an example from CSci 4651 course.