Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

scheme - how to do multiply-all function in RACKET

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 ?rst!

Solution: The data de?nition 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
...)
|#

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For the simplest solution, use apply for this:

(define (multiply-all lst)
  (apply * lst))

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...