Home Ask Login Register

Developers Planet

Your answer is one click away!

oren February 2016

Variadic append function (append any number of lists together)

I'm trying to implement the scheme procedure append myself. The simplest version is to append 2 lists together is quite easy and can be done with:

 (define (append lis1 lis2)
                  (if (null? lis1) 
                    (cons (car lis1)
                          (append (cdr lis1) lis2))))

The trouble starts when you want to append any number of lists. For 0 lists and 1 lists the the idea is simple, but im having a real hard time thinking how to apply this procedure to any number of lists... Any help would be appreciated, Oren


Óscar López February 2016

We just have to repeatedly apply your append function, and foldr is the tool for the job. Try this:

(define (append* . lsts)
  (foldr (lambda (sublist acc)
           (append sublist acc))

For example:

(append* '(1 2) '(3) '(4 5 6) '(7 8))
=> '(1 2 3 4 5 6 7 8)

naomik February 2016

Óscar's answer is good but I would probably reverse the input and use foldl instead as foldl is implemented with a proper tail call.

(define (append* . xs)
  (foldl append null (reverse xs)))

Output is the same

(append* '(1 2) '(3) '(4 5 6) '(7 8))
=> '(1 2 3 4 5 6 7 8)

Post Status

Asked in February 2016
Viewed 3,967 times
Voted 4
Answered 2 times


Leave an answer

Quote of the day: live life