问题
I have tried all kinds of combinations of cons and append to produce '(5 . (5)) but I couldn't. Is there any way?
回答1:
At the risk of sounding like Bill Clinton, it depends on what you mean by "produce".
If you mean "produce a value that prints on the screen as '(5 . (5))
, then you're sort of out of luck, because this value prints as '(5 5)
.
For a similar example: how do I produce the number 1e-1
? Well, try typing it in; this is the same as 0.1, and if you type in 1e-1, it's going to print as 0.1.
However, you can evaluate
#lang racket
(= 0.1 1e-1)
... and you'll see that they're the same number.
In the same way, try evaluating
#lang racket
(equal? '(5 . (5)) (list 5 5))
and you'll see that these are two ways of writing the same value.
回答2:
There is no portable way to print proper list improperly. The easiest one would be write own printer. A very simple one would be something like the following:
(define (write-dot obj . maybe-port)
(define out (if (null? maybe-port) (current-output-port) (car maybe-port)))
(cond ((pair? obj)
(display "(" out)
(write-dot (car obj) out)
(let loop ((obj (cdr obj)))
(display " " out)
(cond ((null? obj))
((and (pair? obj) (null? (cdr obj)))
(display ". " out)
(write obj out))
((pair? obj) (write-dot (car obj)) (loop (cdr obj)))
(else (write obj)))
(display ")" out)))
(else (write obj out))))
来源:https://stackoverflow.com/questions/33991926/scheme-how-to-produce-5-5