Search code examples
formattingschemeracketdouble-quotesquotation-marks

Print raw control characters while preserving string delimiters in output (Racket)


I have a list in Racket like so:

'(some-symbol
  "some\ntext\ngoes in\nhere")

I want to print it out such that control characters like \n are translated to their actual values, in this case a linefeed. However, I also want the quotation marks of the string (i.e., the delimiters) to be preserved in the output a la write or print. The display function already does the first part of what I want, but it strips out quotation marks that are not escaped like \". E.g.:

racket@> (displayln '(some-symbol "some\ntext\ngoes in\nhere")) ;; I want the linefeeds as produced here
(some-symbol some
text
goes in
here)
racket@> (println '(some-symbol "some\ntext\ngoes in\nhere")) ;; But I also want the quotation marks as preserved here
'(some-symbol "some\ntext\ngoes in\nhere")
racket@> 

Is there some way to get this sort of output effect in Racket without escaping string delimiters like \"? Also, I do not want the ' character, which precedes the list, in the output.


Solution

  • It's not clear exactly what you want, so let's put a straw man out there for you to bash around:

    #lang racket
    
    (require rackunit)
    
    ;; find every string in an s-expression, add quotes to it:
    (define (add-quotes s)
      (cond [(list? s)
             (map add-quotes s)]
            [(string? s)
             (string-append "\"" s "\"")]
            [else s]))
    
    (check-equal? (add-quotes '((a b "cde") (("g") f)))
                  '((a b "\"cde\"") (("\"g\"") f)))
    
    ;; display s with quotes around strings:
    (define (funny-display s)
      (display (add-quotes s)))
    

    Not what you wanted?