2

I have issue with representing box structure via LISP's dotted pairs.

CL-USER 21 > (cons 1 (cons (cons 3 4) (cons (cons 3 4) 2)))

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

This is what i have, this is the output, but that's clearly incorrect, because the 3.4 pair is there twice, can someone help me correct this please? It has to be represented with cons(dotted pairs).enter image description here

ive tried to represent it many different ways, but i cant find the solution for this.

dejvoos
  • 33
  • 3

4 Answers4

4

You can create it like this:

CL-USER 1 > (let ((c (cons 3 4)))
              (cons 1
                    (cons c
                          (cons c 2))))
(1 (3 . 4) (3 . 4) . 2)

We don't see it in the printed output, but the sublists are the same object:

CL-USER 2 >  (eq (second *) (third *))
T

We can let Lisp make the structure clear:

CL-USER 3 > setf *print-circle* t
T

CL-USER 4 > ***
(1 #1=(3 . 4) #1# . 2)
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
3

You need to use a variable so you can refer to the same pair in multiple places.

(let ((box34 (cons 3 4)))
  (cons 1 (cons box34 (cons box34 2))))
Barmar
  • 741,623
  • 53
  • 500
  • 612
3

You don't need to declare a specific variable to compose your list, you just need to use the Sharpsign Sharpsign :

CL-USER> (setf foo '(1 #1=(3 . 4) #1# . 2))
(1 (3 . 4) (3 . 4) . 2)

CL-USER> (eq (second foo) (third foo))
T
Jérôme Radix
  • 10,285
  • 4
  • 34
  • 40
0

[This is really a comment not an answer, but it's too long for a comment.]

As you are using LispWorks, you might be interested in using its grapher as a visualisation tool to see cons trees. Here is a function which will do that:

(use-package :capi)

(defun show-cons-graph (c)
  (contain
   (make-instance 'graph-pane
                  :roots (list c)
                  :children-function (lambda (c)
                                       (typecase c
                                         (cons (list (car c) (cdr c)))
                                         (t '())))
                  :print-function (lambda (c)
                                    (typecase c
                                      (cons "")
                                      (t (format nil "~S" c)))))))

Here is

(show-cons-graph (cons 1 (cons (cons 3 4) (cons (cons 3 4) 2)))

not sharing

and here is

(let ((c (cons 3 4)))
  (show-cons-graph (cons 1 (cons c (cons c 2)))))

sharing

ignis volens
  • 7,040
  • 2
  • 12