Class 6: Efficiency in Scheme

Slides

Display version (pdf).

Supplemental Reading

These short, optional readings may help clarify some topics covered in lecture.

Handouts

Homework

Submit your solutions to the following exercises electronically in a file called ex.scm contained in a folder called class06.

Four function definitions are given below. Re-write each of these functions so that they are tail-recursive. Your new functions should have the exact same signature as those below (same name, same arguments). So you will have to write helper functions to do the tail recursion.

  1. ; Computes n!
    (define (fact n)
      (apply * (range 1 n)))
    

  2. ; Adds the sum of squares of the numbers in L
    (define (ssql L)
      (apply + (map sqr L)))
    

  3. (Note: we saw another solution to this problem in class using let.)

    ; Gets the largest number in a list
    (define (maxl L)
      (if (null? (cdr L))
          (car L)
          (max (car L) (maxl (cdr L)))))
    

  4. ; Produces a list of numbers from a to b
    (define (range a b) 
      (if (> a b) 
          null 
          (cons a (range (+ a 1) b))))