append
append
takes two or more lists and constructs a new list
with all of their elements. For example,
(append '(1 2) '(3 4))
returns a list (1 2 3 4)
.
Notice that append
works differently from the way list
does:
(list '(1 2) '(3 4))
returns ((1 2) (3 4))
, a two element list of the lists
it was given. list
makes its arguments
elements of the new list, independent of whether the arguments
are lists or something else.
append
requires that its
arguments are lists, and makes a list whose elements are the
elements of those lists--in this case, a four-element
list. Intuitively, it concatenates the lists it is given.
It only concatenates the top-level structure, however--it
doesn't "flatten" nested structures. For example
(append '((1 2) (3 4)) '((5 6) (7 8)))
returns ((1 2) (3 4) (5 6) (7 8))
append
doesn't modify any of its arguments, but the result of
append
generally shares structure with the last list it's given.
(It effectively conses the elements of the other lists onto the last
list to create the result list.) It's therefore dangerous to make a
"new" list with append and then modify the "old" list. This type of
structure sharing is one of the reasons side effects are discouraged in
Scheme.