if and
condcons, car, cdr, and
cadr and friendslist functionReminder: no class Friday.
First labs are next week (Monday or Tuesday, depending on your section)
Office hours still TBD - planning to announce by Monday of next week.
for or while loops!Basic if conditional syntax:
(if test val-if-true val-if-false)
(define absolute-value ; abs is a builtin
(lambda (x)
(if (< x 0)
(- x)
x)))Equivalent to your familiar if/elseif/elseif/else chain:
(cond ((test1 val-if-test1)
(test2 val-if-test2)
(else val-otherwise)))
(define sign
(lambda (x)
(cond ((< x 0) -1)
((= x 0) 0)
(else 1))))Scheme evaluates everything it sees. Special types like numbers, strings, booleans, etc. evaluate to themselves.
Except in special cases, when Scheme sees (stuff),
it assumes that it’s a procedure call and tries to evaluate it.
(1) ; errors
Exceptions so far - “special forms”:
lambda, let, if,
cond(cons 1 4)
quote: please don’t evaluate this right now(1 . 4) errors(quote (1 . 4)) does not error'(1 . 4)Back to dotted pairs:
(define a (cons 1 4))
(define b (cons (cons 1 2) 3))
Play with car and cdr
Show caar, cdar.
Do Exercises Part A
(define c (cons 1 (cons 2 (cons 3 4))))
(define lst (cons 1 (cons 2 (cons 3 (cons 4 '())))))
'() is the empty list
Recursively defined list. A list is:
c above is not a “proper list”, whereas d
is.
Shorthand: (list 1 2 3 4)
(equal? d (list 1 2 3 4)) ; these are the same!
Again, notice:
(1 2 3 4) ; by itself errors because 1 isn't a procedure
(reverse (1 2)) ; errors
(reverse '(1 2)) or (reverse (list 1 2))
has the intended effect
Do Exercises Part B
Reminder: base case, recursive case
A natural fit for recursively defined structures like lists!
Example: length of a list, recursively.
Do Exercises Part C
Recursive helpers: Example - compute the average in one pass.
;; Return the sum of the given list of numbers
(define sum
(lambda (lst)
(if (null? lst)
0
(+ (car lst) (sum (cdr lst))))))
;; Return the average of the given list of numbers
(define two-pass-avg
(lambda (lst)
(if (eqv? lst '())
#f
(/ (sum lst) (length lst)))));; Helper - average the contents of lst, which is the tail
;; of a list whose prior length-so-far elements sum to sum-so-far.
;; lst: the input list
;; sum-so-far: the sum of elements prior to lst
;; length-so-far: the number of elements prior to lst
(define one-pass-avg ; traverses the list only once
(lambda (lst sum-so-far length-so-far)
(if (null? lst) ; is the empty list
(/ sum-so-far length-so-far)
(one-pass-avg
(cdr lst)
(+ (car lst) sum-so-far)
(+ 1 length-so-far)))))
;; Return the average of the given list of numbers
(define avg ; uses one-pass avg, traverses only once
(lambda (lst)
(one-pass-avg lst 0 0)))