Scheme: Lists of three dotted elements returning strangely (like an infix operator?)
Asked Answered
M

2

6

I am a new Scheme/Racket student, so please excuse any blatant syntax errors.

It came up in class today that the scheme list '(a, b, c) should be invalid, but when we ran it, it returned:

>'(a . b . c)  
(b a c)

Which makes no sense. Afaik, the interpreter should create a cons cell with car 'a and cdr 'b, and the 'c should be invalid. That said, the interpreter is doing something really strange here. This works with #lang scheme, #lang racket, and others. We are using DrRacket as the interpreter.

Interestingly,

>'(a . b . c . d)

throws an exception and dies.

I am very curious and would love to be able to understand this since I am new to the language. Google was very unhelpful (probably since the search terms are kind of ambiguous) Thank you!

EDIT: It might be because '(a . b . c) is interpreted with b as an infix operator. For example: >(4 . + . 6) returns 10. Perhaps the interpreter is using b like an operator? i.e. (b a c) like (+ 4 6), infix-wise.

Expermentation says:

>(define b +)  
>(define a 4)  
>(define c 6)  
>(a . b . c)  
10

So I think this solves the problem, but I still don't fully understand the use of the "." operator in this case. I think we've solved this, but any more insight would be greatly appreciated!

Matter answered 16/9, 2011 at 20:9 Comment(1)
The dots on either side of the operator remind me of Fortran: 1 .LT. 3Camera
L
8

Short answer: you got it. For more information on this Racket-specific use of dots, see the documentation for infix in the Racket docs.

Longevous answered 16/9, 2011 at 20:32 Comment(0)
C
4

It's a special feature of Racket's reader. (See John's answer.)

For other implementations, you can instead use the readable S-expressions reader to be able to read infix expressions. It uses curly braces. e.g., {3 + 4} is read in as (+ 3 4). Even more special (than Racket's infix reader), you can use {3 + 4 + 5} or {3 + 4 + 5 + 6}; they will read as (+ 3 4 5) and (+ 3 4 5 6) respectively.

Cheju answered 16/9, 2011 at 20:42 Comment(1)
See also this implementation of readable S-exps for Racket: planet.racket-lang.org/…Bladdernut

© 2022 - 2024 — McMap. All rights reserved.