Held Monday, February 8
(* 3 (- (+ A 4) 5))
(- (+ A 4) 5)is ``multiply 3 by the result''.
(+ A 4)is ``subtract 5 from the result and then multiply 3 by that new result''.
(lambda (x) (* 3 x))
(lambda (y) (- y 5))
((lambda (x) (* 3 x)) ((lambda (y) (- y 5)) (+ A 4)))
ADD A #4 STO TMP SUB TMP #5 STO TMP SUB #3 TMP
((read) - (read)). Which
(read)is done first? It turns out that it's up to the implementer. If you want the first one done first, you could write
((lambda (first) ((lambda (second) (- first second)) (read))) (read))
(define (prodprimes n) (if (= n 1) 1 (if (prime? n) (* n (prodprimes (- n 1))) (prodprimes (- n 1)))))
prime?is called, it is passed a return address. It must also produce a return value which the code at the return address uses. We can think of that as a function, which me might then name.
Hopefully, this is a topic that most of you know already.
;;; Compute the factorial of n (define (factorial n) (if (= n 0) 1 (* n (factorial (- n 1))))) ;;; Determine whether n is even. A helper function for expt. (define (even n) (= (modulo n 2) 0)) ;;; Computer the square of x. A helper function for expt. (define (square x) (* x x)) ;;; Compute x^n for integer n. Runs in O(log_2 n) time. (define (expt x n) (cond ((= n 0) 1) ((even n) (square (expt x (/ n 2)))) (#t (* x (expt x (- n 1)))))) ;;; Compute x^n for integer n. Runs in O(n) time. (define (ex x n) (if (= n 0) 1 (* x (ex x (- n 1)))))
letrecis a way to define local functions.
(define (factorial n) (letrec ((facthelper (lambda (n acc) (if (= n 0) acc (facthelper (- n 1) (* n acc)))))) (facthelper n 1)))
Disclaimer Often, these pages were created ``on the fly'' with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
This page may be found at http://www.math.grin.edu/~rebelsky/Courses/CS302/99S/Outlines/outline.07.html
Source text last modified Wed Feb 10 09:39:43 1999.
This page generated on Wed Feb 10 09:55:16 1999 by SiteWeaver. Validate this page.
Contact our webmaster at email@example.com