How can I use "cons" without generating nested lists in Schema?

When trying to generate a list of subsets that exist in two sets, I am having a minus problem . The procedure takes a list named result and tries to build a new list from the result and a car of a different set. So far, the set is generated with the correct elements, but they are contained in a nested list of size N , where N is the number of attachments and the number of elements in the subset I am looking for.

How can I apply minus with the 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 call (car list)

and get 1

not((() . 1) . 2)

0


source to share


1 answer


First of all, (((() . 1) . 2) . 3)

it is not a nested list - it is not a list at all. (((() 1) 2) 3)

will be a nested list. (((() . 1) . 2) . 3)

is a dashed pair, the first element of which is also a dashed pair.

So now to explain the behavior you are seeing: In the lisp language family (cons a b)

, a pair is created containing a

how it is car

and b

how it is cdr

.

Now the list is either an empty list ( ()

), or a couple, whose cdr

well is a list ( car

can contain anything - if both cdr

and car

are the list, the list is called a nested list).

A pair that is not a list is called a dot. This is what you are creating here because you are calling cons

with a second argument that is not a list.



Output:

You cannot use cons

to add to the end of the list. If you need to add to the end of the list, you can use concat

with one list of items as the second argument.

Note that adding to the end of the list is an operation O(n)

and adding to the front (using cons

) is an operation O(1)

, so if possible you should change your algorithm so that you only need to add in front.

+2


source







All Articles