CS 451 - Programming Languages - Fall 2007
Scheme
Loyola College >
Department of Computer Science >
Dr. James Glenn >
CS 451 >
Lecture Notes and Examples >
Scheme
lucy:~/451> scheme-elk
> (+ 2 3)
5
> (+ 6 (* 3 5))
21
> (if (> 1 2) 100 10)
10
> (if (> 1 2) 100)
()
> (car (1 2 3 4 5))
car: application of non-procedure: 1
1> (car '(1 2 3 4 5))
1
1> (cdr '(1 2 3 4 5))
(2 3 4 5)
1> (load "functions.scm")
1> (square 20)
400
1> (sum '(1 2 3 4 5))
15
1> (sum '())
0
1> (mymap square '(1 2 3))
(1 4 9)
1> (load "primes.scm")
1> (map isprime '(1 2 3 4 5 6 7 8 9 10))
(#f #t #t #f #t #f #t #f #f #f)
1> (quit)
lucy:~/451>
functions.scm
; squares its argument
(define square
(lambda (x)
(* x x)
)
)
; sums all integers in a list
(define sum
(lambda (l)
(if (null? l)
0
(+ (car l) (sum (cdr l)))
)
)
)
; applies a 1-place function to a list of arguments (like built-in map)
(define
(mymap f l)
(if (null? l)
l
(cons (f (car l)) (mymap f (cdr l)))))
primes.scm
; determines if a divides b (if there is an integer k s.t. b = a*k)
(define divides
(lambda (a b)
(if (= a 0) (= b 0) (if (= (modulo b a) 0) #t #f))
)
)
; given odd f & x, determines if there's a factor y of x s.t. f <= y <= sqrt(x)
(define findfactor
(lambda (x f)
(cond
((> (* f f) x) #f)
((divides f x) #t)
(else (findfactor x (+ f 2)))
)
)
)
; given an integer x, determines if x is prime
(define isprime
(lambda (x)
(cond
((< x 2) #f)
((= x 2) #t)
((and (> x 2) (divides 2 x)) #f)
(else (not (findfactor x 3)))
)
)
)
This code can also be downloaded from the files
functions.scm,
and primes.scm.