[racket-users] Capturing print?

18 views
Skip to first unread message

Kevin Forchione

unread,
Jul 10, 2019, 4:48:08 PM7/10/19
to Racket-Users List
Hi guys,
Is there a wrapper or something like that that I can place around a print expression so that it captures it and returns a string value? Something like:

[capture-print [printf “hello, world!”)) => “hello, world!”

There are times when testing I’d like to capture the output and compare it with a check-equal? and suppress it from displaying in testing It could also be useful in other was possibly for delaying and manipulating printed output.

Kevin

bruno cuconato

unread,
Jul 10, 2019, 4:54:30 PM7/10/19
to Kevin Forchione, Racket-Users List

--
You received this message because you are subscribed to the Google Groups "Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to racket-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/racket-users/CC768C18-C600-4136-8EF7-1A4AAC19BA25%40gmail.com.
For more options, visit https://groups.google.com/d/optout.

Kevin Forchione

unread,
Jul 10, 2019, 7:21:50 PM7/10/19
to bruno cuconato, Racket-Users List


On Jul 10, 2019, at 1:53 PM, bruno cuconato <bcc...@gmail.com> wrote:


Thanks! Yes, I think with a little tinkering I can get that to work for what I have in mind. Took me awhile to discover *how* that is supposed to work! Apparently the proc for with-output-to-string is a thunk:

(with-output-to-string (λ a
                         (printf "a=~a~%" a)
                         (define x 10)
                         (define y 20)
                         (printf "x=~a y=~a~%" x y)))

=> "a=()\nx=10 y=20\n”


Something a little macro can handle:

(define-syntax (output->string stx)
  (syntax-parse stx
    [(_ body:expr ...) #'(with-output-to-string (thunk body ...))]))

(output->string
    (define x 10)
  (define y 20)
  (printf "x=~a y=~a~%" x y))


=> "x=10 y=20\n"


Kevin
Reply all
Reply to author
Forward
0 new messages