-2

These are the outputs of different combinations of arguments to cons. I just started learning lisp. Can someone help me understand these ?

Break 80 [81]> (CONS '(A) 'B) 
((A) . B)
Break 80 [81]> (CONS '(A) '(B)) 
((A) B)
Break 80 [81]> (CONS 'A 'B) 
(A . B)
Break 80 [81]> (CONS 'A '(B)) 
(A B)
Break 80 [81]> 
shrinidhisondur
  • 771
  • 1
  • 8
  • 18
  • 1
    [Here.](http://www.gigamonkeys.com/book/they-called-it-lisp-for-a-reason-list-processing.html) – Mark Karpov Sep 19 '14 at 05:26
  • [**14.1 Cons Concepts**](http://www.lispworks.com/documentation/HyperSpec/Body/14_a.htm) – Joshua Taylor Sep 19 '14 at 11:55
  • +1 for experimenting on your own and methodically trying permutations of inputs combinations (this is good!), but -1 for lack of research effort (you haven't shown any attempt to find any documentation about conses, lists, etc.). – Joshua Taylor Sep 19 '14 at 11:57
  • Also see [Dot notation in scheme](http://stackoverflow.com/q/20216711/1281433). Scheme and Common Lisp are not exactly the same, but that question is applicable to lots (all?) of different languages in the Lisp family. The key you need right now may be that all conses are the same, but certain "combinations" of conses get *printed* in a special way. – Joshua Taylor Sep 19 '14 at 11:59
  • possible duplicate of [Lisp difference between (cons 'a (cons 'b 'c)) and (cons 'a '(b.c))](http://stackoverflow.com/questions/1859505/lisp-difference-between-cons-a-cons-b-c-and-cons-a-b-c) – sds Sep 19 '14 at 12:01

1 Answers1

1

The cons function always does the same thing: it produces a cons cell of its arguments. A cons cell is simply a pair. You can get the first element of the pair with car and the second element with cdr.

For writing a literal cell, you can quote and use the notation (x . y) where x is the car and y is the cdr. Using this notation, you can write your examples as follows (but don't just take my word for it, try it in the REPL):

> '((A) .  B ) ;=> ((A) . B)
> '((A) . (B)) ;=> ((A) B)
> '( A  .  B ) ;=> (A . B)
> '( A  . (B)) ;=> (A B)

But why don't the results of the second and fourth cases print the same way that we wrote them? There are special printing conventions for cons cells, because we use cons cells to implement linked lists.

Read 14.1.2 Conses as Lists for specifics, but a list is a cons cell whose car is the first element of the list, and whose cdr is the rest of the list (i.e., another list). That means that the list (1 2 3) is the same as (using the literal dotted pair notation) (1 . (2 . (3 . nil))). You can try that in the REPL:

> '(1 . (2 . (3 . nil))) ;=> (1 2 3)

That's a very useful printing (and input) convention for a language where lists are so fundamental. I've written more about this in an answer to other questions, too:

Community
  • 1
  • 1
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353