These short, optional readings may help clarify some topics covered in lecture.
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.
; Computes n!
(define (fact n)
(apply * (range 1 n)))
; Adds the sum of squares of the numbers in L
(define (ssql L)
(apply + (map sqr L)))
(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)))))
; Produces a list of numbers from a to b
(define (range a b)
(if (> a b)
null
(cons a (range (+ a 1) b))))