[REBOL] Re: Building an Associate List from a string
From: carl:cybercraft at: 24-Dec-2003 22:42
On 21-Oct-03, Tom Conlin wrote:
> On Mon, 20 Oct 2003, Tim Johnson wrote:
>> Hello REBOLS:
>> I need some advice :-)
>> I've written a function that converts a delimited string into
>> an associative list.
>> Code and example console session is below:
>> ;; >> make-al: function[ {Builds an associative list from a delimited
>> string}
>> str[string!] {delimited string}
>> /with delimiter[string! char!] {custom delimiter (TAB is
>> default)}
>> /default _dval[any-type!] {custom default value (NONE is
>> default)}
>> ][tmp al-block sep dval][
>> sep: either with[to-string delimiter][to-string TAB]
>> dval: either default[_dval][none]
>> al-block: copy []
>> tmp: parse/all str sep
>> if not even? length? tmp[append tmp dval]
>> foreach [name value] tmp[
>> append al-block to-word name
>> append al-block value
>> ]
>> al-block
>> ]
>> test: "age^-54^-name^-Tim Johnson^-occuptation^-coder"
>> probe make-al test
>> ;; = Console session >> == [age "54" name "Tim Johnson" occuptation "coder"]
>> ;; Now, so far it is a piece of cake, but this is where
>> ;; I falter:
>> I would like to employ a strategy that converts any value
>> to the best guess for a rebol datatype. IOWS, "54"[string!]
>> would become 54[integer!]
>> It occurs to me that a brute-force method would be to process
>> via a nested attempt[any[]] loop.
>> Any more "elegant" ideas?
>> thanks
>> tim
> could try
> append al-block load value
Hmm - I should've looked at the function properly. :) (See my
previous post, which you can disregard due to what I say below about
syntax errors using load.)
With "... load value" as Tom suggests above, names such as "Tim
Johnson" would be converted to two words and not a string, so a check
for spaces and perhaps other characters would be needed to prevent
that. ie, you'd return a string if a space was discovered. Another
problem would be syntax errors when load hits text it can't recognise
as a valid datatype. So, an error check would be needed too, with a
string returned if you did get an error.
I get the feeling though you'd be better to force what datatype they
should be based on the names encounted, (ie, age = decimal,
occupation = string), as the format of your data may not ever be
quite right to always do a correct conversion.
--
Carl Read