Reputation: 744
I am new to lisp. I am trying to read numbers from user and want to store it as a list. For example: if the user enters 1 2 3 4 5
, then the list would contain 5 elements (1 2 3 4 5)
. I tried (parse-integer(read-line) :junk-allowed t)
but it returns only the first element. How should I do this? Thanks.
Upvotes: 2
Views: 3255
Reputation: 60004
read
The simplest option is to ask the user to enter the list (with the parens) and just call (read)
.
The second option is to put the parens yourself:
(read-from-string (concatenate 'string "(" (read-line) ")"))
Note that the power of the Lisp reader can put you in trouble. E.g., if the user types #.(start-ww3)
instead of (1 2 3)
at your prompt, you might not reach your bomb shelter in time.
This means that you must bind *read-eval*
to nil
when calling read
on text you do not control.
parse-integer
repeatedlyFinally, you can call parse-integer
in a loop
(defun parse-integers (s &optional (start 0))
(loop with num do
(setf (values num start) (parse-integer s :start start :junk-allowed t))
while num collect num))
or recursively:
(defun parse-integers (s &optional (start 0))
(multiple-value-bind (num end)
(parse-integer s :start start :junk-allowed t)
(and num (cons num (parse-integers s end)))))
Upvotes: 6