我正在尝试创建一个包含n个数字的递归函数。该函数应该做的是取n个数字的乘积,然后取n个根。我得到了n个数字的乘积,但是不知道如何实现第n个根。
我尝试做的是实现 expt x y 函数,但是在recursion中无法正确实现。而且,当尝试实现此功能时,我也不知道如何将expt函数提供给第n个根。 (y = 1 / n) 。
(define (nth-root-of-product-of-numbers lst)
(cond [(empty? lst) 1]
[else (* (first lst) (nth-root-of-product-of-numbers (rest lst)))]))
因此,以上代码在n个数字的列表上正确生成乘积,但是不能补偿第n个根问题。输入示例如下:
(check-within
(nth-root-of-product-of-numbers (cons 9 (cons 14 (cons 2 empty)))) 6.316359598 0.0001)
答案 0 :(得分:3)
您需要在递归结束时计算第n个根。有几种方法可以做到这一点-例如,定义帮助程序以查找产品并在计算出产品后取根:
(define (nth-root-of-product-of-numbers lst)
(define (product lst)
(cond [(empty? lst) 1]
[else (* (first lst) (product (rest lst)))]))
(expt (product lst) (/ 1 (length lst))))
一种更有效的解决方案是编写一个尾递归过程,并传递元素数量,以避免最后计算length
。使用named let
的方法如下:
(define (nth-root-of-product-of-numbers lst)
(let loop ((lst lst) (acc 1) (n 0))
(cond [(empty? lst)
(expt acc (/ 1 n))]
[else
(loop (rest lst) (* (first lst) acc) (add1 n))])))
一个更惯用的解决方案是使用内置过程来计算产品:
(define (nth-root-of-product-of-numbers lst)
(expt (apply * lst) (/ 1 (length lst))))
无论如何,它可以按预期工作:
(nth-root-of-product-of-numbers (list 9 14 2))
=> 6.316359597656378