user1048677
user1048677

Reputation: 239

How to parse a string as a list structure?

I have a string, which holds a a list structure like ((p X) (q (f X))) and I would really like to find a function that interprets/converts this string as a list of lists just like if it was a '((p X) (q (f X))).

(list "((p X) (q (f X)))") just makes it a single element list.

(intern "((p X) (q (f X)))") encloses it in | symbols.

Upvotes: 2

Views: 3350

Answers (2)

Rainer Joswig
Rainer Joswig

Reputation: 139411

"((p X) (q (f X)))" is a string in Lisp. Strings are enclosed in ".

LIST creates a list with its arguments as elements.

So (list "((p X) (q (f X)))") creates a list with the string as the element.

INTERN creates a symbol.

(intern "((p X) (q (f X)))") creates a symbol with the string argument as its name. In Common Lisp symbols can have arbitrary names, even including characters like ( and ). Such symbols are printed enclosed in |. Example: |((p X) (q (f X)))| is a symbol with such a strange name.

Parsing an s-expression is called reading in Lisp. The functions to do so are for example READ and READ-FROM-STRING.

There are two basic ways to read the s-expression:

CL-USER 1 > (read-from-string "((p X) (q (f X)))")
((P X) (Q (F X)))
17

But you can also open an input stream based on the string using WITH-INPUT-FROM-STRINGand then use the usual READ:

CL-USER 2 > (with-input-from-string (stream "((p X) (q (f X)))")
              (read stream))
((P X) (Q (F X)))

Upvotes: 3

Trey Jackson
Trey Jackson

Reputation: 74480

How does

(read-from-string  "((p X) (q (f X)))")

work for you? Documentation found here.

Upvotes: 8

Related Questions