Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a string with a fill pointer in Common Lisp?

I want to use formatted output in a loop to generate a string. Manual says it can be easily done by giving format function a string with a fill pointer as a destination. Unfortunately, it is not transparent from the manual how to initialize this string in the first place.

I tried (string "") and (format nil "") with no luck.

(make-array 0 :element-type 'character :fill-pointer 0) did work for me, but it just doesn't feel right.

What is the proper way to initialize a string with a fill pointer?

like image 431
akalenuk Avatar asked Aug 07 '13 07:08

akalenuk


2 Answers

(make-array estimated-size-of-final-string
            :element-type 'character :fill-pointer 0)

(with :adjustable t too if the estimate is inaccurate) is one way; for accumulating output to produce a string it may be more idiomatic to use with-output-to-string:

(with-output-to-string (stream)
  (loop repeat 8 do (format stream "~v,,,'-@A~%" (random 80) #\x)))

=>

"----------------------------------x
--------x
--------------------------------------x
----------------------------------------------------------------x
--------------x
-----------------------------------------x
---------------------------------------------------x
-----------------------------------------------------------x
"
like image 161
huaiyuan Avatar answered Nov 09 '22 08:11

huaiyuan


(make-array 0 :element-type 'character :fill-pointer 0) is the canonical way (well, it's quite possible to use an initial non-zero length and use :initial-contents with a string value). It's also possible to specify the fil-pointer value as t, that will set the fill-pointer at the end of the string.

like image 6
Vatine Avatar answered Nov 09 '22 08:11

Vatine