我试图建立一个递归函数,它包含一个n个数字的列表。这个函数应该做的是取n个数的乘积,然后取第n个根。我得到了n个数字的乘积,但不知道如何实现第n个根。
我尝试的是实现expt 函数,但是在递归中没有正确实现它。此外,在尝试实现此函数时,我也不知道如何才能将expt函数提供给nth根。(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)发布于 2019-02-09 23:29:35
您需要计算递归末尾的第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。下面是如何使用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.316359597656378https://stackoverflow.com/questions/54609436
复制相似问题