Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 789
Erty Seidohl Avatar asked Sep 16 '11 20:09

Erty Seidohl


2 Answers

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

like image 156
John Clements Avatar answered Nov 20 '22 21:11

John Clements


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.

like image 43
Chris Jester-Young Avatar answered Nov 20 '22 21:11

Chris Jester-Young