开发者

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

开发者 https://www.devze.com 2023-04-05 05:33 出处:网络
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:

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 sea开发者_如何转开发rch 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!


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号