Midhun
Midhun

Reputation: 744

LISP:How to read numbers from user and store as a list

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

Answers (1)

sds
sds

Reputation: 60004

Use 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) ")"))

safety and security

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.

Call parse-integer repeatedly

Finally, 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

Related Questions