How to convert a string to list using clisp?

2019-02-17 04:49发布

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.

7条回答
看我几分像从前
2楼-- · 2019-02-17 04:59

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.

查看更多
孤傲高冷的网名
3楼-- · 2019-02-17 05:04

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))
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-17 05:05

I see that Svante is right. My previous attempt did not work. Here is another attempt. I use concatenate to change the string into a list representation. Then I use read-from-string to convert the string (s-2) into an actual list.

(setf s-0 "1 2 3 4 5 6 7")
(setf s-1 (concatenate 'string "(" s ")" ))
(setf s-2 (read-from-string s-1))

I roll it into a function like this:

(defun from-string-to-list (s)
  (let ((L (read-from-string 
           (concatenate 'string "(" s ")"))))
    L))

The only purpose of "let" and "L" is to make the function from-string-to-list return only the list and not return multiple values. read-from-string returns two values: The list and the size of the string, I think.

查看更多
一纸荒年 Trace。
5楼-- · 2019-02-17 05:13

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)))
查看更多
我想做一个坏孩纸
6楼-- · 2019-02-17 05:14

That would do,

(with-input-from-string (s "1 2 3 4 5")
   (let ((r nil))
      (do ((line (read s nil 'eof)
                 (read s nil 'eof)))
          ((eql line 'eof))
          (push line r))
   (reverse r)))
查看更多
Root(大扎)
7楼-- · 2019-02-17 05:18

Hint: Take a look at with-input-from-string.

查看更多
登录 后发表回答