While attempting to generate a list of subsets that exist within two sets, I am running into an issue with cons. A procedure takes in a list named result and attempts to construct a new list out of result and the car of another set. So far, the set is generated with the correct elements, but they are contained within a size N nested list, where N is the number of nestings and the number of elements within the subset for which I am searching.
How can I apply cons with result without creating a nested list?
Example:
;These are two sets that I will be checking
(define s1 '(1 2 3 4))
(define s2 '(1 2 3))
;Result from running these lists through my procedure
(((() . 1) . 2) . 3)
;What I want to have generated
(1 2 3)
I need to be able to call (car list)
and receive 1
not ((() . 1) . 2)
First of all
(((() . 1) . 2) . 3)
is not a nested list - it's not a list at all.(((() 1) 2) 3)
would be a nested list.(((() . 1) . 2) . 3)
is a dotted pair whose first element is also a dotted pair.So now to explain the behaviour you see: In the lisp family of languages
(cons a b)
creates a pair containinga
as it'scar
andb
as itscdr
.Now a list is either the empty list (
()
) or a pair whosecdr
is also a list (thecar
might contain anything - if both thecdr
and thecar
are a list, the list is called a nested list).A pair that is not a list is called a dotted pair. This what you're creating here because you're calling
cons
with a second argument which is not a list.Conclusion:
You can not use
cons
to append to the end of the list. If you need to append to the end of a list, you can useconcat
with a single-element list as the second argument.Note however that appending to the end of a list, is an
O(n)
operation while appending at the front (usingcons
) is anO(1)
operation, so if possible you should change your algorithm, so it only needs to append at the front.