From a66038a42761b31c2d883d621bae7a1c6ed03910 Mon Sep 17 00:00:00 2001 From: Matthew Flatt Date: Fri, 7 Dec 2018 11:03:53 -0700 Subject: [PATCH] io: shortcut for common `format` patterns --- racket/src/io/demo.rkt | 12 +++++++++ racket/src/io/format/main.rkt | 46 ++++++++++++++++++++++++++++------- 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/racket/src/io/demo.rkt b/racket/src/io/demo.rkt index f08456bf3e..f8563bc157 100644 --- a/racket/src/io/demo.rkt +++ b/racket/src/io/demo.rkt @@ -91,6 +91,18 @@ #:property prop:custom-write (lambda (v o mode) (fprintf o "<~a>" (animal-name v)))) +(test "apple" (format "~a" 'apple)) +(test "apple" (format "~a" "apple")) +(test "apple" (format "~a" #"apple")) +(test "#:apple" (format "~a" '#:apple)) +(test "17.5" (format "~a" 17.5)) + +(test "apple" (format "~s" 'apple)) +(test "\"apple\"" (format "~s" "apple")) +(test "#\"apple\"" (format "~s" #"apple")) +(test "#:apple" (format "~s" '#:apple)) +(test "17.5" (format "~s" 17.5)) + (test "1\n\rx0!\"hi\"" (format "1~%~ \n \rx~ ~o~c~s" 0 #\! "hi")) (test "*(1 2 3 apple\t\u0001 end file 1\"2\"3 #hash((a . 1) (b . 2)))*" diff --git a/racket/src/io/format/main.rkt b/racket/src/io/format/main.rkt index def8484c2c..2d71fff43a 100644 --- a/racket/src/io/format/main.rkt +++ b/racket/src/io/format/main.rkt @@ -3,18 +3,13 @@ "../port/parameter.rkt" "../port/output-port.rkt" "../port/string-port.rkt" + "../string/convert.rkt" "printf.rkt") -(provide format - fprintf +(provide fprintf printf - eprintf) - -(define/who (format fmt . args) - (check who string? fmt) - (define o (open-output-string)) - (do-printf 'printf o fmt args) - (get-output-string o)) + eprintf + format) (define/who (fprintf o fmt . args) (check who output-port? o) @@ -28,3 +23,36 @@ (define/who (eprintf fmt . args) (check who string? fmt) (do-printf who (current-error-port) fmt args)) + +;; ---------------------------------------- + +(define (general-format fmt args) + (check 'format string? fmt) + (define o (open-output-string)) + (do-printf 'format o fmt args) + (get-output-string o)) + +(define (simple-format a) + (cond + [(boolean? a) (string-copy (if a "#t" "#f"))] + [(number? a) (number->string a)] + [(symbol? a) (symbol->string a)] + [(keyword? a) (string-append "#:" (keyword->string a))] + [else #f])) + +(define format + (case-lambda + [(fmt a) + (cond + [(or (equal? fmt "~a") (equal? fmt "~A")) + (or (simple-format a) + (cond + [(bytes? a) (bytes->string/utf-8 a #\?)] + [(string? a) (string-copy a)] + [else (general-format fmt (list a))]))] + [(or (equal? fmt "~s") (equal? fmt "~S")) + (or (simple-format a) + (general-format fmt (list a)))] + [else (general-format fmt (list a))])] + [(fmt . args) + (general-format fmt args)]))