0

I have tried all kinds of combinations of cons and append to produce '(5 . (5)) but I couldn't. Is there any way?

Bibrak
  • 544
  • 4
  • 20
  • 1
    Can you show your best try? So we can point you to the error and how to correct it. – Renzo Nov 30 '15 at 06:48
  • 2
    I can't think of a way to get Racket to output exactly that – if the `cdr` of a pair is a proper list, it's not printed as a dotted pair. It would be better to ask how to create a specific structure than how to get a specific output format. – molbdnilo Nov 30 '15 at 09:21
  • 1
    Can you tell us why you need the list represented like that? What procedure is consuming this result and why does it need it like that? – Eric Clack Nov 30 '15 at 11:57
  • 5
    Look at this question: [Dot notation in scheme](http://stackoverflow.com/q/20216711/1281433). The structure you want is just `(list 5 5)` or `(cons 5 (cons 5 '()))`, or `'(5 5)` or `'(5 . (5))`, etc. But the standard printing will always be `(5 5)`. – Joshua Taylor Nov 30 '15 at 18:36
  • Yes, I got it. Its the matter with the printer not the internal structure. – Bibrak Dec 02 '15 at 21:31

2 Answers2

7

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.

John Clements
  • 16,895
  • 3
  • 37
  • 52
1

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))))
Takashi Kato
  • 646
  • 3
  • 5