2013年4月24日 星期三

NCNU LISP HW5


For 1.31, you have to write the `term' function.
That is (the fucntion will return a float.)
              (term 1) --> 2/3 = 0.6666666...
              (term 2) --> 4/3 = 1.3333333...
              (term 3) --> 4/5 = 0.8
              
For 1.32, you have to write the `accumulate'. It can be done either in the way of linear recusive or linear iterative. Only one version is required.

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

(define (term x)
(do-term x 2 3)
)
(define (do-term x numerator denominator)
   (cond ((= x 1)   (/ (* numerator 1.0) denominator))
((even? x) (do-term (- x 1) (+ numerator 2) denominator))
(else      (do-term (- x 1) numerator (+ denominator 2)))
   )
)
(define (even? n)
        (= (remainder n 2) 0)
)



(define (accumulate combiner null-value term1 a next b)
(if (> a b) null-value
                    (combiner (term1 a) (accumulate combiner null-value term1 (next a) next b))
)
)

(define (product term2 a next b)
(accumulate * 1 term2 a next b)
)
(define (sum term3 a next b)
(accumulate + 0 term3 a next b)
)
(define (inc x)
(+ x 1)
)
(define (identify x)
x
)

1 則留言:

  1. 老師說我的TERM速度有點慢= =||

    Your `term' is O(n)!

    回覆刪除