Scheme: how to produce '(5 . (5))

旧巷老猫 提交于 2019-12-13 20:12:42

问题


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

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