Skip to main content

write-sequence

write-sequence Function

Syntax:

write-sequence sequence stream &key start end → sequence

sequence—a sequence.

stream—an output stream.

start, endbounding index designators of sequence. The defaults for start and end are 0 and nil, respectively.

Description:

write-sequence writes the elements of the subsequence of sequence bounded by start and end to stream.

Examples:

(write-sequence "bookworms" \*standard-output\* :end 4) 
▷ book
"bookworms"

Side Effects:

Modifies stream.

Exceptional Situations:

Should be prepared to signal an error of type type-error if sequence is not a proper sequence. Should signal an error of type type-error if start is not a non-negative integer . Should signal an error of type type-error if end is not a non-negative integer or nil.

Might signal an error of type type-error if an element of the bounded sequence is not a member of the stream element type of the stream.

See Also:

Section 3.2.1 (Compiler Terminology), read-sequence, write-string, write-line

Notes:

write-sequence is identical in effect to iterating over the indicated subsequence and writing one element at a time to stream, but may be more efficient than the equivalent loop. An efficient implementation is more likely to exist for the case where the sequence is a vector with the same element type as the stream.

Expanded Reference: write-sequence

Basic Usage

write-sequence writes the elements of a sequence to an output stream and returns the sequence.

(with-output-to-string (s)
(write-sequence "hello world" s))
=> "hello world"

Using :start and :end

The :start and :end keywords write only a portion of the sequence.

(with-output-to-string (s)
(write-sequence "bookworms" s :end 4))
=> "book"
(with-output-to-string (s)
(write-sequence "abcdefgh" s :start 2 :end 6))
=> "cdef"

Writing Byte Sequences

write-sequence works with binary streams and byte vectors.

(with-open-file (out "/tmp/cl-ws-test.bin"
:direction :output
:element-type '(unsigned-byte 8)
:if-exists :supersede)
(write-sequence #(10 20 30 40 50) out))

(with-open-file (in "/tmp/cl-ws-test.bin"
:element-type '(unsigned-byte 8))
(let ((buf (make-array 5 :element-type '(unsigned-byte 8))))
(read-sequence buf in)
buf))
=> #(10 20 30 40 50)

Return Value

write-sequence returns the original sequence.

(with-output-to-string (s)
(let ((result (write-sequence "test" s)))
(write-char #\Space s)
(write-string (string-upcase result) s)))
=> "test TEST"