Common Lisp Newbie Tip: with-ouput-to-string
▁ dec 20 2007
Common Lisp newbie tip of the day: I found this one while trying to find out how to make a function redirect output from a stream to a string that I could put in a variable. Sending nil to format will make it return a string, but any function using format will have to collect the results from the calls to format.
The solution is quite simple. The macro with-output-to-string will create a character output stream quite easily:
CL-USER> (with-output-to-string (stream)
(print stream)
(difflib:unified-diff stream "foobar" "foozot"))
#<SB-IMPL::STRING-OUTPUT-STREAM {1538C419}>
"---
+++
@@ -1,6 +1,6 @@
f
o
o
-b
-a
-r
+z
+o
+t"
Difflib here is from CL-DIFFLIB. Quite handy!