Difference between cons and list function call in elisp
Asked Answered
H

3

6

In elisp,

(cons 1 2) `returns`
(1 . 2)
(list 1 2) `returns`
(1 2)

What is the difference between both the outputs?

Hyposensitize answered 27/12, 2014 at 12:56 Comment(2)
The first is a single cons cell, the second is a list made up of two cons cells linked to each other.Januarius
in the first case, isn't '1' the first cons cell with '2' as its cdr & '2' - the second cons cell with nil cdr? what do you mean when you say, it is a single cons cell?Hyposensitize
J
4

(cons 1 2) creates a single cons cell like this:

---------  
| 1 | 2 |   
---------

Lists in Lisp are a chain of cons cells. Each cell's car is a list element, its cdr points to the next cell in the chain; the last one's cdr points to the special symbol nil. So (list 1 2) creates a chain of cons cells like this:

--------|   --------|
| 1 | ----->| 2 | ----> nil
--------|   --------|

It's equivalent to (cons 1 (cons 2 nil))

Januarius answered 27/12, 2014 at 13:9 Comment(0)
S
1

If you have two things, A and B, you have as a given that (eq (car (cons A B)) A) and (eq (cdr (cons A B)) B). That is, cons constructs a "cons cell" (a pair) with two parts, the car part and the cdr part.

By convention, a pair that consists of an atom and the empty list is considered to be a list. So, (cons 2 nil) is (2). By that same token, (list 1 2) returns a similar structure to (cons 1 (cons 2 nil)) (that is, (1 2)).

Seriate answered 28/12, 2014 at 18:3 Comment(0)
Z
0

the job of cons is to add the first element to the second element so, in your first example (cons 1 2) the 2 is an element so adding 1 to it will create a pair (1 . 2)

the second example creates a list with 1 and 2 as element of that list

if it was like (cons 1 (list 2)) now cons will find that the second parameter is a list and the result will be (1 2)

Zworykin answered 27/12, 2014 at 13:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.