Reputation: 110093
How would I do something like the following in scheme?
printf("I went to the park at %d with %s", 4, "Bob");
The closest I have right now is:
(define TIME 4)
(define NAME "Bob")
(display "I went to the park at ") (display TIME) (display " with ") (display NAME) (display ".")
Upvotes: 1
Views: 2210
Reputation: 21318
You can't do this in standard Scheme. Many Scheme implementations have a format
procedure that is modeled on the Common Lisp format
. For example, Chez Scheme has a pretty complete implementation of format
, and also printf
which is just a wrapper around format
. I am so used to using format
that I never think to use printf
in lisps:
> (format #t "I went to the park at ~A with ~A~%" 4 "Bob")
I went to the park at 4 with Bob
> (printf "I went to the park at ~A with ~A~%" 4 "Bob")
I went to the park at 4 with Bob
Here format
sends the output to the current output port when the first argument is #t
; printf
automatically sends output to the current output port. Common Lisp style format directives are prefixed with a tilde (~
). The ~A
, or aesthetic, directive prints objects in human-readable form, and is what you want most of the time. There are other directives for formatting numbers; I added the ~%
directive, which emits a newline. Your original example did not include a newline, and printf
, at least in C, does not add a newline at the end of output (ordinarily this is desirable). The format
procedure should allow much more control over results than the mother of all printf
s, namely C's fprintf
.
The specific facilities for printing formatted output will depend on the implementation, but Chez Scheme, MIT Scheme, Gauche Scheme, and Guile all implement format
. Chicken Scheme implements format
, and also implements printf
, fprintf
, and sprintf
which all use the same format directives as format
. Racket has a host of formatted output procedures, including format
, printf
, and fprintf
; all of these use Common Lisp style format directives, too.
You will have to consult the documentation of a specific implementation to understand which format directives are supported and how they work; the Chez Scheme documentation contains some information, but suggests consultation of the Common Lisp HyperSpec for complete documentation.
There are also SRFI-28 (Basic Format Strings) and SRFI-48 (Intermediate Format Strings) which provide some of this functionality to implementations that support them.
Upvotes: 4
Reputation: 235984
It really depends on what Scheme interpreter you're using. For example, in Racket you can use printf
for a similar effect:
(printf "I went to the park at ~a with ~a" 4 "Bob")
=> I went to the park at 4 with Bob
Check the documentation for more formatting modifiers.
Upvotes: 2