What's the difference between using cons to combine an element to a list and using cons to combine a list to an element in scheme?
Furthermore, how exactly does cons work? Does it add element to the end of the list or the beginning?
Thanks!
What's the difference between using cons to combine an element to a list and using cons to combine a list to an element in scheme?
Furthermore, how exactly does cons work? Does it add element to the end of the list or the beginning?
Thanks!
The primitive
cons
simply sticks together two things, the fact that some of those things are considered lists is incidental. For instance, this works and creates a pair (also known as a cons cell):Now, if the second argument to
cons
happens to be a list, then the result will be a new list, and the first argument tocons
will be added at the head of the old list. In other words: to create a list you need a list, even if it's empty:But if the second argument to
cons
is not a list, then the result will be just a pair, or an improper list, meaning that it doesn't end in'()
as it should to be considered a list:Just to clarify, you can't use
cons
to add elements at the end of a list. The usual way to build a list is going from right-to-left, adding elements in reverse at the head position - say you want to build the list'(1 2 3)
, then you have tocons
the elements in the order3 2 1
:For those rare occasions where you need to add one element at the end (and believe me, doing so generally means that you're thinking the algorithm wrong) you can use
append
, which receives two lists as arguments: