简体   繁体   中英

Scheme - Finding the sum of fractions from -n to n

So I have to make a function called frac-sum the takes the sum of a fraction of two functions from -n to n so f(n)/g(n) as the fraction and the sum from -n to n so f(-n)/g(-n) + ... f(n)/g(n)

It takes three formal parameters fg and n.

So far I have this which should work but ends up going in a recursive loop meaning there is something wrong with my base case:

    (define (negn n) (- (* n -1) 1))
    (negn 1)

    (define (frac-sum f g n)
      (cond ((= n (negn n)) 0)
            ((= (g n) 0) (+ 0 (frac-sum f g (- n 1))))
            ((+ (/ (f n) (g n)) (frac-sum f g (- n 1))))))

And I used this to test it which should output two:

(frac-sum (lambda (x) (- x 1)) (lambda(x) x) 1)

There does not exist an integer n for which the statement n = (n * -1) - 1 will hold true. This is the cause of your function's infinite loop.

Since you want to iterate over the range [-n, n] , you can define the two values in your function, and either increment the lower bound, or decrement the upper bound recursively. You can then terminate the function by testing whether the lower bound is equal to the upper bound.

(define (frac-sum f g n)
  (let loop ((neg (- n)) (pos n) (acc 0))
    (cond
      ((= neg pos) acc)
      ((zero? (g neg))
       (loop (add1 neg) pos acc))
      (else
       (loop (add1 neg) pos (+ (/ (f neg) (g neg)) acc))))))

For example:

(frac-sum (lambda (x) (- x 1)) (lambda (x) x) 1)
=> 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM