about the dot “.” in scheme

南楼画角 提交于 2019-12-06 10:55:57

The dot symbol is displayed when you build a cons-pair or a list which is not proper (meaning: it doesn't end with the empty list). For example:

(cons 1 2) 
=> (1 . 2) ; a cons-pair

(cons 1 (cons 2 (cons 3 4)))
=> '(1 2 3 . 4) ; an improper list

For instance, to display an output such as the one shown in the question try this:

(define lst1 '(1 2 3))
(define lst2 '(4 5))

(list (cons (car lst1) (car lst2))
      (cons (cadr lst1) (cadr lst2)))

=> '((1 . 4) (2 . 5))

Although . can be a part of a symbol, . is not in itself a valid symbol. . is used in list structure as a divider between the car and the cdr. eg. (a . (b . (c . ()))) ; ==> (a b c).

Practical application is the historic use as a rest argument in the prototype of a procedure and you can use it as template an transformation of macros. Also, read can read it in and you can use it as data like (define lst '((a) . (b))).

So to recap:

(a . b) is a pair of a and b, while (a.b) is the same as (a.b . ()) thus a pair of the symbol a.b and the empty list.

As for how to create a pair you use cons. (cons 'a 'b) => (a . b) while (list a b) => (cons 'a (cons b '())). Now you can make a pair with two lists as arguments, (cons '(1 4) '(2 5)) but if you print it you know that (a . (b)) is the same as (a b) thus (cons '(1 4) '(2 5)) will display as ((1 4) 2 5) since it will prefer not to display the dot. If it would prefer to show dots it would have displayed it as ((1 . (4 . ())) . ((2 . (5 . ())))) instead since thats how many pairs there are in that data structure.

If you have managed to get the output ((1 4) (2 5)) and really wanted ((1 . 4) (2 . 5)) you need to replace a list with cons.

It's called a dotted pair and is produced when you cons an item with a non-list, such as:

> (cons 1 2)
(1 . 2)

See: http://download.plt-scheme.org/doc/html/guide/Pairs__Lists__and_Scheme_Syntax.html

From R7RS:

The most general notation (external representation) for Scheme pairs is the “dotted” notation (c1 . c2) where c1 is the value of the car field and c2 is the value of the cdr field. For example (4 . 5) is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the external repre- sentation of a pair, not an expression that evaluates to a pair.

. is not a symbol.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!