Search code examples
listschemeracketlist-manipulation

In scheme how do you add an element to a list a certain number of times?


so the function would take 3 elements a number item and a list. I want to add the item to the list how ever many times the number says so if i did (pad-front 3 'a '(b c)) it would return (a a a b c) as the list. I think i would want to cons the item to the list and just do that n times im just not sure on how to get it to do it.


Solution

  • In Racket this is easy using built-in procedures:

    (define (pad-front n x lst)
      (append                   ; append together both lists
       (build-list n (const x)) ; create a list with n repetitions of x
       lst))                    ; the list at the tail
    
    (pad-front 3 'a '(b c))
    => '(a a a b c)
    

    ... But I guess you want to implement it from scratch. The idea is the same as above, but using only primitive procedures; I'll give you some hints so you can figure out the details. Fill-in the blanks:

    (define (pad-front n x lst)
      (if <???>            ; base case: if `n` is zero
          <???>            ; then return the tail list
          (cons <???>      ; else cons the element to be repeated
                (pad-front ; and advance the recursion
                 <???>     ; subtract one unit from `n`
                 x lst)))) ; pass along `x` and `lst`
    

    Notice that the trick is to keep adding the x element until no more repetitions are needed (in other words: until n is zero). At that point, we just stick the tail list at the end, and we're done!