scheme - how to do multiply-all function in RACKET -


exercise 22.5.11 develop function multiply-all takes in list of numbers , returns result of multiplying them together.
for example: (check-expect (multiply-all (cons 3 (cons 5 (cons 4 empty)))) 60)
hint: “right answer” empty list? may not think @ first!

solution: data definition similar list-of-strings:

; list-of-numbers either ; empty or ; nelon (non-empty list of numbers). #| (define (function-on-lon l) ; l list of numbers (cond [ (empty? l) ...] [ (cons? l) (function-on-nelon l)] )) |# ; nelon looks ; (cons number lon ) #| (define (function-on-nelon l) ; l cons ; (first l) number ; (rest l) lon ; (function-on-lon (rest l)) whatever returns ...) |# 

any suggestions?

for simplest solution, use apply this:

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

if need build procedure scratch, remember base case (an empty list) should return 1, , recursive step should multiply current value using standard solution template, this:

(define (multiply-all lst)   (if (empty? lst)       1       (* (first lst)          (multiply-all (rest lst))))) 

for nicer answer, 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 procedures work expected:

(multiply-all '()) => 1 (multiply-all '(3 5 4)) => 60 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

android - Inheriting from Theme.AppCompat* -