Lisp - String I/O



String I/O means reading/writing strings from/to various types of data sources ranging from strings, files and standard input/output. Let's discuss various options with examples.

Reading from Strings

Lisp provides read-from-string function and with-input-from-string macro to read LISP objects from strings.

Using read-from-string function

  • read-from-string function parses a string in same way as it is an input from a stream.

  • This function reads LISP object from string and returns the same.

; read an expression from String
(print(read-from-string "(+ 1 2)"))

Output

When you execute the code, it returns the following result −

(+ 1 2)

Using with-input-from-string macro

  • with-input-from-string macro creates a temporary stream using a string.

  • We can use standard input function like read, read-line on it thereafter.

; read inputs from string
(with-input-from-string (in "(10 20 30)")
   ; run a loop item read from stream
   (loop for x = (read in nil)
        while x
        do (print x))) ; print each number

Output

When you execute the code, it returns the following result −

(10 20 30)

Writing to Strings

Lisp provides format function and with-output-to-string macro to write LISP objects to strings.

Using format function

  • format function is a very powerful function with multiple formatting options to write formatted output to strings.

  • By passing nil as first argument, format output is directed to a string.

; assign evaluated expression to output
(defvar output (format nil "The value is ~a" 40))

; print the output
(print output)

Output

When you execute the code, it returns the following result −

"The value is 40"

Using with-output-to-string macro

  • with-output-to-string macro creates a temporary output stream from a string.

  • We can use standard output functions like print, princ and write within the macro.

; create an array temp
(setq temp (make-array '(0) :element-type 'base-char :fill-pointer 0 :adjustable t)) 

; write a string to temp array
(with-output-to-string (s temp)
   (format s "Hello, World!")
   (input-stream-p s))
 
; print the array
(print temp)

Output

When you execute the code, it returns the following result −

Hello, World!

Key Considerations

LISP String I/O capabilities are very flexible and provides a powerful tool to work with strings in various ways. String I/O seemlessly integrates with other I/O operations using macros, making it very easy to work with varying sources.

Advertisements