Question

Complete the Scheme procedure, (repeats-a-lot lst), that takes in a list of non­negative inte­ gers and returns a list containing, in order, each value represented the number of times equal to its value.  See examples below.  You may use reverse in your solution.  You may also use helper pro­ cedures in your solution and the back of this page for more space.

NOTE: this is not a for homework. it's a practice question and I just can't get the answer

Was it helpful?

Solution

I'll give you some hints so you can solve this practice question yourself, filling the blanks. The first and possibly most useful thing you can do, is splitting the problem in two procedures. The first one, given a number n takes care of producing a list with i repetitions of n:

(define (repeat n i)
  (if (zero? i)               ; if no more repeats are needed
      <???>                   ; return the empty list
      (cons <???>             ; else cons `n` and advance the recursion
            (repeat <???>     ; `n` is left unchanged
                    <???>)))) ; but `i` is diminished by one

The second procedure uses the previous one as a helper, iterating over the input lst and combining the results of all of the sublists produced by repeat:

(define (repeats-a-lot lst)
  (if (null? lst)                      ; if the list is empty
      <???>                            ; return the empty list
      (append (repeat <???> <???>)     ; append n repetitions of current element
              (repeats-a-lot <???>)))) ; and advance the recursion over the list

There are several possible ways to solve this problem, some fancier (using tail recursion, using a fold procedure, etc.) but this IMHO is the simplest way, in the sense that it only requires knowledge of some basic list manipulating procedures. Anyway, it works as expected:

(repeats-a-lot '(1 2 3))
=> '(1 2 2 3 3 3)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top