qmack
qmack

Reputation: 49

Adding a single element onto a list until a certain point

I want to make a function that given a list and a natural number, adds zeros onto the list so the length of the list equals the natural number. What is an efficient way of doing this so instead of making every element zero, it does what it's supposed to do

(define (zero-list loz alon)
  (cond
    [(empty? loz) empty]
    [(= (-(length loz) 1) alon) (cons 0 loz)]
    [else (cons 0 (zero-list (rest loz)))]))

Example: (zero-list (list 1 2 3) 5)) -> (list 0 0) so (length (list 1 2 3)) + (length (list 0 0)) = 5

Upvotes: 0

Views: 37

Answers (1)

Atharva Shukla
Atharva Shukla

Reputation: 2137

Use make-list to generate a list that has the appropriate number of 0s (i.e. difference between the number and the length of the input list):

(define (zero-list l n) 
  (make-list (- n (length l)) 0))

(zero-list (list 1 2 3) 5) ; -> (list 0 0)

Upvotes: 1

Related Questions