listschemelispconsthe-little-schemer

Scheme: When I cons two atoms I am getting a dot in the middle. Why?


When I do a cons on two atoms, I am getting a . in between.

1]=>(cons 'one 'two)
;Value 1: (one . two)

Why I am getting the . operator. Does it have any meaning? I am using mit-scheme.

I have seen this stackoverflow link but not clear.

UPDATE: The definition of cons in Little Schemer states that, cons takes two arguments, the first one is any S-expression and the second one is any list.


Solution

  • The dot is just the way Scheme displays a cons cell when the cdr part is not itself a cons cell or the empty list. The dot is not an operator in this case, for example:

    (cons 1 2)
    => '(1 . 2) ; a cons pair, a.k.a. a cons cell
    
    (cons 1 (cons 2 3))
    => '(1 2 . 3) ; not a proper list, it doesn't end in '()
    

    If the cdr part is a cons cell or the empty list '(), then we have a list:

    (cons 1 '())
    => '(1) ; a proper list, ends in '()
    
    (cons 1 (cons 2 '()))
    => '(1 2) ; a proper list, ends in '()
    

    The definition in The Little Schemer is a simplification, in reality cons can take any type of value for each one of its arguments. By convention if the second argument is a list it'll be considered a list and displayed as such, otherwise it's a plain old cons cell and the dot is there to remind you of this.