Convert any value to string

Problem

You need a procedure that will convert any value to a string.

Solution

(define-values (displayed written)
  (let ((repr (lambda (fn)
                (lambda (object)
                  (call-with-port (open-output-string)
                                  (lambda (port)
                                    (fn object port)
                                    (get-output-string port)))))))
    (values (repr display) (repr write))))

Credit: Jakub T. Jankiewicz

SRFI

The procedures displayed and written are also defined by SRFI 166.

Usage

(define (print x)
  (display x)
  (newline))

(print (written #\x))
;; ==> #\x

(print (written "foo"))
;; ==> "foo"

(print (written '(1 2 3)))
;; ==> (1 2 3)

Back to the Scheme Cookbook