How to convert a string to list using clisp?
14,171
Solution 1
Hint: Take a look at with-input-from-string.
Solution 2
Here is a recursive solution.
;Turns a string into a stream so it can be read into a list
(defun string-to-list (str)
(if (not (streamp str))
(string-to-list (make-string-input-stream str))
(if (listen str)
(cons (read str) (string-to-list str))
nil)))
Solution 3
You should use parse-integer
in a loop.
For example, using loop
:
(let ((string "1 2 3"))
(loop :for (integer position) := (multiple-value-list
(parse-integer string
:start (or position 0)
:junk-allowed t))
:while integer
:collect integer))
⇒ (1 2 3)
If you need better control about the splitting, use the split-sequence
or cl-ppcre
library.
If you need to parse more general number formats, use the parse-number
library.
Libraries are available from Quicklisp.
Solution 4
(with-input-from-string (s "1 2 3 4 5 6 7" :index i :start 0 :end 13)
(list (read s) (read s) (read s) (read s) (read s) (read s)))
(1 2 3 4 5 6 7)
it works however i feel it is not so elegant as there are many read
call .
thanks again!
Solution 5
I think this might work:
(setf s "1 2 3 4 5 6 7")
(setf L-temp (coerce s 'list))
This makes a list with spaces as elements. Remove spaces:
(setf L-final (remove #\Space L-temp))
Related videos on Youtube
Comments
-
z_axis almost 2 years
How can i convert the string
"1 2 3 4 5 6 7"
into the list(1 2 3 4 5 6 7)
elegantly? I am using CLISP. -
mange over 12 years
(with-input-from-string (s "1 2 3 4 5 6 7") (loop for x = (read s nil :end) until (eq x :end) collect x))
should work, but note that it will take"one two three"
to a list of symbols rather than a list of strings. -
sçuçu over 10 yearsadditionally, in the above form, in the first list you can replace a string, here
"1 2 3 4 5"
, with a form like(read-line stream)
, to read a line from a stream yet not yielding a string but a list. -
Svante about 7 yearsThis produces the list
(#\1 #\2 #\3 #\4 #\5 #\6 #\7)
, i. e. a list of digit characters. Aside: don'tsetf
variables that do not exist. -
Indinfer about 7 yearsI see Svante is correct. I tried again and posted the answer using read-from-string. I'm still beginning to learn Lisp. So, I am curious about not "setf variables that do not exist". Is that a violation of functional style? Or does it make my code more confusing in larger programs?
-
Svante about 7 yearsNo, it is just undefined behaviour. You are implicitly creating a global variable that may or may not be special (dynamic). Use
defparameter
ordefvar
to create a new globally special variable, or uselet
(or other constructs introducing a local scope) to create local variables. -
Indinfer about 7 yearsI appreciate your explanation, Svante. Thank you.