如何在RACKET中做所有乘法运算 [英] how to do multiply-all function in RACKET
问题描述
练习22.5.11 开发一个函数multiple-all,它接受一个数字列表,并返回将所有数字相乘的结果.
例如:
(check-expect (multiply-all (cons 3 (cons 5 (cons 4 empty)))) 60)
提示:空列表的正确答案"是什么?一开始可能不是您想的那样!
Exercise 22.5.11 Develop a function multiply-all that takes in a list of numbers and returns the result of multiplying them all together.
For example:
(check-expect (multiply-all (cons 3 (cons 5 (cons 4 empty)))) 60)
Hint: What is the "right answer" for the empty list? It may not be what you think at first!
解决方案:数据定义类似于字符串列表:
Solution: The data definition is similar to that for list-of-strings:
; A list-of-numbers is either
; empty or
; a nelon (non-empty list of numbers).
#|
(define (function-on-lon L)
; L a list of numbers
(cond [ (empty? L) ...]
[ (cons? L) (function-on-nelon L)]
))
|#
; A nelon looks like
; (cons number lon )
#|
(define (function-on-nelon L)
; L a cons
; (first L) a number
; (rest L) a lon
; (function-on-lon (rest L)) whatever this returns
...)
|#
有什么建议吗?
推荐答案
对于最简单的解决方案,请为此使用apply
:
For the simplest solution, use apply
for this:
(define (multiply-all lst)
(apply * lst))
如果您需要从头开始构建过程,只需记住基本情况(一个空列表)应返回1
,并且递归步骤应使用标准解决方案模板乘以当前值,如下所示:>
If you need to build the procedure from scratch, just remember that the base case (an empty list) should return 1
, and the recursive step should multiply the current value using the standard solution template, like this:
(define (multiply-all lst)
(if (empty? lst)
1
(* (first lst)
(multiply-all (rest lst)))))
要获得更好的答案,您可以尝试使用尾部递归:
For a nicer answer, you can try using tail recursion:
(define (multiply-all lst)
(let loop ([lst lst] [acc 1])
(if (empty? lst)
acc
(loop (rest lst) (* (first lst) acc)))))
无论如何,这些程序都能按预期工作:
Anyway the procedures work as expected:
(multiply-all '())
=> 1
(multiply-all '(3 5 4))
=> 60
这篇关于如何在RACKET中做所有乘法运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!