Search code examples
schemelisprepl-printed-representation

Can one use cons to do ((a . b) . (c . d)) and if not any other means or dot pair cannot have 2nd element like this?


;;; <- can one use cons to do  ((a . b) . (c . d))?


(define x (cons a b)); nil -- should it be error
(define x (cons 'a 'b)); (a . b)

(define y (cons 'c 'd)); (c . d)

(define z00 (cons x y)) ; (((a . b) c . d) <- cannot use cons to do  ((a . b) . (c . d))?
(define z01 (cons x 'y)) ; ((a . b) . y) 
(define z10 (cons 'x y)) ; (x c . d) 
(define z11 (cons 'x 'y)); (x . y))

(define z (list x y z00 z01 z10 z11)) 
        ; ((a . b) (c . d) ((a . b) c . d) ((a . b) . y) (x c . d) (x . y))

;;; and if not any other means or dot pair cannot have 2nd element like this?


Solution

  • Pairs visualize differently based on their content. If the cdr of a pair contains the empty list it is a proper list an dthe dot and extra empty list is not shown:

    (cons 'a '())
    '(a . ())
    ; ==> (a)
    

    A pair that has pair as it's cdr can be visualized as a list element without the . and extra parenthesis:

    (cons 'b '(a))
    '(b . (a))
    ; ==> (b a)
    (cons 'b '(a . c))
    '(b . (a . c))
    ; ==> (b a . c)
    

    These are just made so that we can have (1 2 3) displayed instead of (1 . (2 . (3 . ()))) which is how it really is made.

    If you were to not have a pair or a empty list in the cdr then it falls back to showing the dotted pair:

    (cons 'a 'b)
    '(a . b)
    ; ==> (a . b)
    

    In your example '((a . b) . (c . d)) because there is a pair after a dot (eg. the cdr if the pair the visualization will remove the dot and one pair of parentheses and show it like ((a . b) c . d). This is the only acceptable correct way for a REPL to display this even though both your example and the display will be read in as the same structure.

    There is a similar issue with numbers. In code you can use 10, #xa and #o12 to get the number 10 and the value will have no idea what format is was read in as and only show the base 10 in the REPL.