Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do ((A.B).(C.D)) in lisp

I'm trying to figure out how to do this using cons:

((A . B) . (C . D))

where (A . B) and (C . D) are in each cons cell

I've tried doing this (cons (cons 'a 'b) (cons 'c 'd)) but it gives me this:

((A.B) C . D)

I also tried this: (cons (cons 'a 'b) (cons (cons 'c 'd) ())) but it gives me this:

((A . B) (C . D))

Any idea how to achieve this?

like image 597
darkwingcode Avatar asked Dec 15 '10 01:12

darkwingcode


2 Answers

The first one is what you want. They're equivalent. You can verify like this:

1 ]=> (cons (cons 'a 'b) (cons 'c 'd))

;Value 11: ((a . b) c . d)

1 ]=> (car (cons (cons 'a 'b) (cons 'c 'd)))

;Value 12: (a . b)

1 ]=> (cdr (cons (cons 'a 'b) (cons 'c 'd)))

;Value 13: (c . d)

Remember a list is a cons cell. The "car" is the head element of the list or the first half of the cons cell, and the cdr is the rest of the list, or the second element of the cons cell.

Another way to verify that they're equivalent:

1 ]=> '((a . b) . (c . d))

;Value 14: ((a . b) c . d)
like image 52
Laurence Gonsalves Avatar answered Oct 07 '22 07:10

Laurence Gonsalves


Just look at what you get back when you enter in a literal ((A . B) . (C . D)):

* '((a . b) . (c . d))

((A . B) C . D)

There is a defined algorithm the Lisp printer uses to print out data structures built from pairs. Basically, you can't ever get a cons to be printed as a dotted pair inside parentheses when it is the CDR of another cons.

However, it is possible to re-configure the printer so that you get the behavior you are seeking, via SET-PPRINT-DISPATCH:

(set-pprint-dispatch 'cons
  (lambda (stream object)
    (format stream "(~W . ~W)" (car object) (cdr object))))
* '((a . b) . (c . d))

((A . B) . (C . D))
* (cons (cons 'a 'b) (cons 'c 'd))  ;The same object

((A . B) . (C . D))

Although in spite of that it would frankly be better in the long run if you got comfortable with reading the default behavior.

like image 25
Nietzche-jou Avatar answered Oct 07 '22 08:10

Nietzche-jou