Recitation 7

Today's idea: Fun with list functionals: recursion with map
 

Symbols and Quote Special Form

From yesterday's lecture:

Exercise 0: Substitution

Replace every occurrence of a symbol in a list with another symbol.
For example:

(substitute 'w 'r '(r a s c a l l y   r a b b i t))
 > (w a s c a l l y w a b b i t)
 

Exercise 1: Cartesian Product

Cartesian product of two sets s and t is: Represent set as a list without duplicates.
Now cartesian-product has type: list<A>, list<B> -> list <A x B>

Example

Questions Exercise

Exercise 2: Powerset

Powerset of a sets s is: Represent set as a list without duplicates.
Now powerset has type: list<A> -> list <list<A>>

Example

Questions Exercise

Exercise 3: Permutations

Permutation of a list p is: Permutation function has type: list<A> -> list <list<A>>

Example

Questions Exercise Hints



Definitions Used

(define (accumulate f base p)
    (cond
      ((null? p) base)
      (else (f (car p) (accumulate f base (cdr p))))))

(define remove (lambda (item x) ... (hidden for now: part of PS3)


Definitions We Developed

(define (subs p from to)
  (if (null? p)
      p
      (let ((e (if (equal? (car p) from)
                   to
                   (car p))))
        (cons e
              (subs (cdr p) from to)))))

(define (subs p from to)
  (map (lambda (x) (if (equal? x from) to x)) p))

(define (cartesian-product p q)
  (cond ((null? p) '())
        (else (append
               (map (lambda (x) (cons (car p) x)) q)
               (cartesian-product (cdr p) q)))))

(define (powerset s)
  (if (null? s)
      (list '())
      (let ((ps (powerset (cdr s))))
        (append
         (map
          (lambda (x) (cons (car s) x))
          ps)
         ps))))

(define (permutations p)
  (if (null? p)
      '(())
      (accumulate append '()
                  (map (lambda (first-item)
                         (map (lambda (perm) (cons first-item perm))
                              (permutations (remove first-item p))))
                       p))))



Daniel Jackson
September 28, 1999