Convert string to list?

Notices and updates
Locked
methodic
Posts: 58
Joined: Tue May 10, 2005 5:04 am

Convert string to list?

Post by methodic »

I have a string whose contents look like this:
(S A (S (V B (N (N C) (P D (N (N E) F))))) X)

My question is, how do I convert this to a list so I can use it with functions like ref-all? I've tried playing around with eval as it seems most appropriate, but wasn't able to get very far with that.

Thanks in advance.

DrDave
Posts: 126
Joined: Wed May 21, 2008 2:47 pm

Re: Convert string to list?

Post by DrDave »

Does list do enougfh for you?
(set 'astring "(S A (V B D) E)")
(list astring)
--> ("(S A (V B D) E)")
But maybe you actually want a simple flat list like (S A V B D E) ? If so, you have to first strip the quotes from the list, then apply flat.

From the looks of your example string, I suspect you built it from a list any way. So don't you already have the list available to you?
...it is better to first strive for clarity and correctness and to make programs efficient only if really needed.
"Getting Started with Erlang" version 5.6.2

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Post by cormullion »

Perhaps you can do this:

Code: Select all

(set 's {(S A (S (V B (N (N C) (P D (N (N E) F))))) X)})
(eval-string (append "'" s))
; so
(ref-all 'N (eval-string (append "'" s)))
;-> ((2 1 2 0) (2 1 2 1 0) (2 1 2 2 2 0) (2 1 2 2 2 1 0))
Also, now, there's read-expr:

Code: Select all

(ref-all  'N (read-expr s))
((2 1 2 0) (2 1 2 1 0) (2 1 2 2 2 0) (2 1 2 2 2 1 0))

DrDave
Posts: 126
Joined: Wed May 21, 2008 2:47 pm

Post by DrDave »

Thanks for the reminder about read-expr. Now we can readily convert a string to a list without even applying list.

Code: Select all

(set 's {(S A (S (V B (N (N C) (P D (N (N E) F))))) X)})
(set 'list-from-string (read-expr s))
-->(S A (S (V B (N (N C) (P D (N (N E) F))))) X)
(list? list-from-string)
-->true
...it is better to first strive for clarity and correctness and to make programs efficient only if really needed.
"Getting Started with Erlang" version 5.6.2

methodic
Posts: 58
Joined: Tue May 10, 2005 5:04 am

Post by methodic »

cormullion wrote:Perhaps you can do this:

Code: Select all

(set 's {(S A (S (V B (N (N C) (P D (N (N E) F))))) X)})
(eval-string (append "'" s))
; so
(ref-all 'N (eval-string (append "'" s)))
;-> ((2 1 2 0) (2 1 2 1 0) (2 1 2 2 2 0) (2 1 2 2 2 1 0))
Also, now, there's read-expr:

Code: Select all

(ref-all  'N (read-expr s))
((2 1 2 0) (2 1 2 1 0) (2 1 2 2 2 0) (2 1 2 2 2 1 0))
That worked great, read-expr is a great new addition! Thanks again!!

Locked