;recursive procedure
(define (accumulate combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a) (accumulate combiner null-value term (next a) next b))))
(define (sum term a next b)
(accumulate + 0 term a next b))
(define (product term a next b)
(accumulate * 1 term a next b))
;iterative procedure
(define (accumulate-iter combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(inter (next a) (combiner (term a) result))))
(iter a null-value))
Trying to evaluate (f f) will get error "object 2 is not applicable". The
process of evaluating (f f)
is as follows:
(f f) ---> apply prodedure f with parameter f
(f 2) ---> apply procedure f with parameter 2
(2 2) ---> at this point, scheme procedure tries to find a procedure named
"2", which does not exist, thus gives back the error message.
So in this case, the parameter of procedure "f" should always be a procedure.
(define tolerance 0.00001)
(define dx 0.00001)
(define (fixed-point f first-guess)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess)
(let ((next (f guess)))
(if (close-enough? guess next)
next
(try next))))
(try first-guess))
(define (deriv g)
(lambda (x)
(/ (- (g (+ x dx)) (g x)) dx)))
(define (newton-transform g)
(lambda (x)
(- x (/ (g x) ((deriv g) x)))))
(define (newtons-method g guess)
(fixed-point (newton-transform g) guess))
(define (cubic a b c)
(lambda (x) (+ (* x x x) (* a (* x x)) (* b x) c)))
;No value 1 ]=> (load "hw3_3.scm") ;Loading "hw3_3.scm" -- done ;Value: cubic 1 ]=> (newtons-method (cubic 10 5 0) 1) ;Value: 7.942367246941882e-11 1 ]=> (newtons-method (cubic 5 15 10) 1) ;Value: -.8788890222278306 1 ]=> (transcript-off)
(define (make-rat n d)
(let ((g (gcd n d)))
(cond ((< d 0) (cons (- (/ n g)) (- (/ d g))))
((> d 0) (cons (/ n g) (/ d g)))
((= d 0) (cons n "Illegal Denom!")))))
(define (cons x y)
(lambda (m) (m x y)))
(define (car z)
(z (lambda (p q) p)))
(define (cdr z)
(z (lambda (p q) q)))
(define (gcd a b)
(if (= b 0)
a
(gcd b (remainder a b))))
(define (numer x)
(car x))
(define (denom x)
(cdr x))
(define (print-rat x)
(newline)
(display (numer x))
(display "/")
(display (denom x)))
(define (make-rat n d)
(let ((g (gcd n d)))
(cond ((< d 0) (cons (- (/ n g)) (- (/ d g))))
((> d 0) (cons (/ n g) (/ d g)))
((= d 0) (cons n "Illegal Denom!")))))
;No value 1 ]=> (load "hw3_5.scm") ;Loading "hw3_5.scm" -- done ;Value: cdr 1 ]=> (define a (make-rat 2 3)) ;Value: a 1 ]=> (print-rat a) 2/3 ;No value 1 ]=> (numer a) ;Value: 2 1 ]=> (denom a) ;Value: 3 1 ]=> (transcript-off)