2

I need to create a pair that contains two pairs inside using Common Lisp.

The output needs to be: ((1 . 2) . (3 . 4))

Literature states (cons (cons 1 2) (cons 3 4)) should output what I need but when I run that I obtain:
((1 . 2) 3 . 4)

Any help is appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Higgins
  • 21
  • 2
  • possible duplicate of [Dot notation in scheme](http://stackoverflow.com/questions/20216711/dot-notation-in-scheme) That question is asking about the case in Scheme, but Common Lisp and Scheme's conses and printing conventions are the same. It might not be a duplicate (note 'possible'), but I the answer there that explains the printing conventions of cons cells and dots will explain why `((1 . 2) 3 . 4)` and `((1 . 2) . (3 . 4))` are just different visual representations of the same thing. – Joshua Taylor Dec 24 '14 at 13:19

4 Answers4

8

In Lisp

((1 . 2) . (3 . 4))

and

((1 . 2) 3 . 4)

are exactly the same thing. You can check by evaluating '((1 . 2) . (3 . 4)).

If you think about it the 3 is the car of the cdr, so it's the second element of the improper list, so the pair (1 . 2) is the first element, 3 as second element and that has 4 instead of NIL to terminate it.

They're just two ways to see the very same cons cells configuration: enter image description here

6502
  • 112,025
  • 15
  • 165
  • 265
2
CL-USER 4 > (equal '((1 . 2) . (3 . 4))
                   '((1 . 2)    3 . 4 ))
T
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
1

#xA is the exact same as 10, but when it's printed it's system settings that dictates how a number is to be printed. The reason is that the fixnum doesn't have a base, but the visual representation does. Just as #xA is the same as 10, ((1 . 2) . (3 . 4)) is the same as ((1 . 2) 3 . 4).

The illusion is that we have lists. In order to do that we display pairs with either nil or a pair as tails differently than pairs that has other values as their tail.. A list (1 2) is modeled as (1 . (2 . ())). The rules are something like this: Whenever the tail is nil or a pair you can omit this pair dot and the first parenthesis of the tail. Apply it recursively and (1 . (2 . ())) displays as (1 2) and ((1 . 2) . (3 . 4)) displays as `((1 . 2) 3 . 4).

To make the illusion complete the reader does the reverse so when it reads (1 2) it creates (1 . (2 . ())) in memory.

To really be a good Lisp programmer (in any dialect) you need to be able to see the omitted dot and parentheses in (1 2). When you do it becomes obvious what you need to do with (a (b c) d) in order to retrieve c (It's obviously (cadadr '(a (b c) d))). When you do master this you'll "see" ((1 . 2) . (3 . 4)).

Sylwester
  • 47,942
  • 4
  • 47
  • 79
-2

This will do it: (cons (cons 1 2) (cons (cons 3 4) empty))

Good luck!