COMP 320: Programming Languages
Simple Scheme Examples
These are the expressions and functions from the Intro to Functional Programming via Scheme video.
Note:
- The
=function can be used to test the equality of numeric expressions. - The
eq?function tests whether 2 items refer to the same object in memory; its behavior with numbers is implementation-dependent. - The
equal?function tests whether 2 items are structurally equivalent with the same values, even if not the exact same object in memory, and so can be used with either atoms or lists. - The
eqv?function does numeric comparisons on numbers (like=), and identity comparisons (likeeq?) on anything else.
In the examples below, = or equal? would have been a better choice.
(print "Hello world!")
(* 3 7)
(+ 3 7)
(+ 3 7 1 21 4)
(sqrt 16)
; some relational operators
(< 3 15)
(eq? 8 15) ;; (= 8 15) would be better test for numbers
(eq? 8 (* 2 4)) ;; (= 8 (* 2 4)) would be better test for numbers
(eq? 8 '(8)) ;; (equal? 8 '(8)) would be a better choice
(max 3 7)
(max 3 7 1 21 4)
; if/then expressions: (if <condition> <then-expr> <else-expr>)
(if (> 3 7) 3 7)
(define (myMax a b) (if (> a b) a b))
(myMax 8 15)
(myMax 82 15)
; myMax only looks at 1st 2 operands
(myMax 82 15 63 4 93)
; simple recursion example showing define, null?, eq?, #t, #f
(define (contains aVal aList)
(if (null? aList) #f ; base case
(if (eq? aVal (car aList)) ; is 1st element it?
#t ; then true
(contains aVal (cdr aList))) ; else check rest of list recursively
))
; example of cond (multi-way conditional), null?, list?, zero?
(define (numZeros ls)
(cond
((null? ls) 0) ; base case
((list? (car ls)) ; is 1st elt a list?
(+ (numZeros (car ls)) (numZeros (cdr ls))))
((zero? (car ls)) ; is 1st elt a 0?
(+ 1 (numZeros (cdr ls))))
(else (numZeros (cdr ls))) ; how many in rest of list?
))
; new version of myMax that looks through list, not just 1st 2
(define (myMax2 ls)
(cond
((null? ls) '()) ; base case, return empty list
((null? (cdr ls)) (car ls)) ; only 1 elt in list, return it
((> (car ls) (myMax2 (cdr ls))) (car ls)) ; 1st elt is max
(else (myMax2 (cdr ls))) ; return max from rest of list
))