[英]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) 因此,我必须制作一个名为frac-sum的函数,将两个函数从-n到n的分数之和作为f(n)/ g(n)作为分数,并将从-n到n的总和作为f( -n)/ g(-n)+ ... f(n)/ g(n)
It takes three formal parameters fg and n. 它采用三个形式参数fg和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) (分数总和(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. 没有整数
n
,语句n = (n * -1) - 1
会成立。 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. 由于要在
[-n, n]
范围内进行迭代,因此可以在函数中定义两个值,然后递归增大下限或减小上限。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.