Converting numbers to strings and strings to lists

A couple of simple but useful functions.
Hopefully this will save someone several hours of scouring Google.

To test the code, copy and paste it into the Nyquist Prompt effect and press the DEBUG button to see the output

; function to convert a number to a string
(defun number-to-string (number)
  (format nil "~a" number))

; function to convert a string into a list
(defun string-to-list (string)
  (read (make-string-input-stream (format nil "(~a)" string))))

; TEST THE FUNCTIONS:
; first make a string
(setq mystring (strcat "1 2 3 " (number-to-string 4)))

; then turn it into a list
(setq mylist (string-to-list mystring))

; then print it out in the debug window
(dotimes (i (length mylist))
  (print (nth i mylist)))

(format nil "I hope you clicked the Debug button...nn :=)")

This topic seems to be a bit outdated but the string-to-list-function was exactly what I needed for changing label tracks with nyquist. With integer and float values it works great but with text I got some surprising results, for example:

(print (string-to-list "999    D-Major 45 Em   2.1 A 4.0001 Test .123456789"))

leads to

(999 D-MAJOR 45 EM 2.1 A 4.0001 TEST 0.123457)

Returned Text is given in uppercase except strings. Therefore I extended this function to avoid
every text in uppercase:

(defun string-to-list (string)
  (mapcar #'str-to-num (remove "" (read (make-string-input-stream 
    (format nil "(\"~a\")" (string-replace " " "\" \"" string)  ))) :test 'equal)  ))

Now the above print-command leads to:

(999 "D-Major" 45 "Em" 2.1 "A" 4.0001 "Test" 0.123457)

which is more appropriate for me (" should be avoided in the string).
“string-to-list” needs a helping function, that I haven’t found as
a build-in in Nyquist:

(defun string-replace (old new str)
  (let ((len (length old)) (pos 0) (posnew 0) (newstr "") )
    (loop
      (setf posnew (string-search old str :start pos))
      (when (null posnew) 
        (setf newstr (format nil "~a~a" newstr (subseq str pos) ))
        (return newstr))
      (setf newstr (format nil "~a~a~a" newstr (subseq str pos posnew) new ))
      (setf pos (+ posnew len)))))

This substring-replacing-function is necessary to put quotes around all elements in the string to avoid uppercases. I needed a further function that I derived from number-string-p in “aud-do-support.lsp” to convert back all strings that are numbers:

(defun str-to-num (str)
  (let ((num (string-to-number str)))
    (if (numberp num)
        num
        str)))

Limitations of this function are discussed in Numbered Labels.
Maybe this code can be helpful for any other.
Good luck,
Joerg

I wrote that post 13 years ago.

Manipulating text in Nyquist is painful, but of course that is not the primary focus of the language.