简体   繁体   中英

How to do a multiplying table on Scheme/Racket

So im extremely new to Scheme, and i've been trying to do a multiplying table, if you put (multiplying-table 10 3) should give a list (3 6 9 12 15 18 21 24 27 30)

Here is my code

(define (multiplying-table n value)
  (cond ((= n 0) '())
        (else (* n value)(Multiplying-table(- n 1)))))

You need to use cons to combine the first number 3 with the list of the rest.

Eg. (3 6 ...) is (cons 3 (cons 6 ...)) . You are instead having two expressions where the (* n value) is only for effect since the result is never used. Because of that every call should return the empty list.

Usually there are 2 ways to do it. With recursion inside cons or with an accumulator. Since lists are created from end to beginning you could count n downwards and build the list from end to beginning. The base case would just return the accumulator which by default is the empty list. Here is an example:

(define (sequence from to)
  (let loop ((n to) (acc '()))
    (if (< n from)
        acc
        (loop (- n 1) (cons n acc)))))

(sequence 5 10) ; ==> (5 6 7 8 9 10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM