CSCI 301 L01 Notes

Lecture 1 - Notes

Outcomes

Racket 2

Announcements

Functional Programming Mind-bends

Conditionals

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))))

Evaluation

(1) ; errors

Exceptions so far - “special forms”:

Dotted pairs

(cons 1 4)

Aside: quoting

Back to dotted pairs:

(define a (cons 1 4))

(define b (cons (cons 1 2) 3))

Do Exercises Part A

Lists

(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

Recursive Solutions

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)))