Cons element for displaying a list of vs cons for an element in a schema

What is the difference between using cons to combine an element into a list and using cons to combine a list into an element in a schema?

Also, how exactly do the cons work? Does the item add to the end of the list or the beginning?

Thanks!

+9
list lisp scheme cons
source share
1 answer

The cons primitive simply combines two things, the fact that some of these things are considered random lists. For example, this works and creates a pair (also known as a cons cell):

 (cons 1 2) => '(1 . 2) ; a pair 

Now, if the second argument to cons is a list, the result will be a new list, and the first argument to cons will be added at the head of the old list. In other words: to create a list, you need a list, even if it is empty:

 (cons 1 '(2 3)) => '(1 2 3) ; a list (cons 1 (cons 2 '())) => '(1 2) ; a list (cons 1 '()) => '(1) ; a list 

But if the second argument cons not a list, then the result is only a pair or an invalid list, which means that it does not end with '() , since it should be considered a list

 (cons '(1 2) 3) => '((1 2) . 3) ; a pair, not a list (cons 1 (cons 2 3)) => '(1 2 . 3) ; an improper list 

To clarify, you cannot use cons to add items at the end of a list. The usual way to create a list goes from right to left, adding elements in the opposite direction in the main position - let's say you want to create a list '(1 2 3) , then you should cons elements in order 3 2 1 :

 (cons 3 '()) ; list is '(3) (cons 2 (cons 3 '())) ; list is '(2 3) (cons 1 (cons 2 (cons 3 '()))) ; list is '(1 2 3) 

In those rare cases when you need to add one element at the end (and, believe me, this usually means that you are mistaken in the algorithm), you can use the append , which receives two lists as arguments:

 (append '(1 2 3) '(4)) => '(1 2 3 4) 
+22
source share

All Articles