[REBOL] Associative data store Re:(4)
From: rebol:techscribe at: 14-Sep-2000 18:28
Hi Keith,
You could use the & function like this:
>> assoc: [a 3]
== [a 3]
>> print mold assoc
[a 3]
>> assoc/a
== 3
Now let's add a new key / value pair using &, the new key will be called
new-key
>> & assoc/new-key 4
== [a 3]
>> assoc/new-key
== 4
>> print mold assoc
[new-key 4 a 3]
And another new key/value pair:
>> & assoc/zz "yet another new key/value pair."
== [new-key 4 a 3]
>> assoc/zz
== "yet another new key/value pair."
>> print mold assoc
[zz "yet another new key/value pair." new-key 4 a 3]
We can also add deeper levels:
>> assoc: [a 1]
== [a 1]
>> print mold a
== [a 1]
>> assoc/a
== 1
Let's create a two-level new path that we will address as a/b/c (where b/c
is the new path in a that we are creating)
>> & assoc/b [c 3]
== [a 1]
>> print mold assoc
[b [c 3] a 1]
>> assoc/b
== [c 3]
>> assoc/b/c
== 3
Now for the & function that makes it possible:
&: func ['_p [path!] _v /local _b] [
_b: copy/part :_p (subtract length? :_p 1)
if value? :_b [
insert _b reduce [last :_p _v]
]
]
At 07:13 PM 9/14/00 -0400, you wrote:
>I really like the path idea. Is there any way to emulate an associative
>array without having to make a special object type?
>
>Very unfortunately, Rebol doesn't let you just do things like:
>assoc/key: "value"
>
>(if assoc/key doesn't actually exist yet)
>
>is there any way to cheat and do something like:
>
>(fake example that doesn't work)
>
>assoc: make hash! []
>change assoc/key "dude"
>
>--------------------------------------------------------------------
>It would be really really nice if RT could give us something like this (hint
>hint):
>
>assoc: make associative! []
>assoc/key: "value"
>
>'first could give us the keys
>and 'second could give us the values
>
>Bonus is, it doesn't require any new syntax... no funky assoc{'key'} or
>anything. :)
>
>Keith
>
>----- Original Message -----
>From: <[rebol--techscribe--com]>
>To: <[list--rebol--com]>
>Sent: Thursday, September 14, 2000 5:57 PM
>Subject: [REBOL] Associative data store Re:(2)
>
>> Oh, shucks,
>>
>> a bug:
>>
>> >assoc-add: func [assoc [block!] candidates [block!] /local found] [
>> > if is-assoc? assoc [
>> > foreach [key value] candidates [
>> > either found: contains-key? assoc key [
>> > insert at assoc/values index? found value
>>
>> The line
>>
>> > insert at assoc/values index? found value
>>
>> Should be
>>
>> change at assoc/values index? found value
>>
>> > ][
>> > insert assoc/keys key
>> > insert assoc/values value
>> > ]
>> > ]
>> > return true
>> > ]
>> > return false
>> >]
>>
>> To quote Joel, "silly me" :-).
>>
>>
>>
>> ;- Elan [ : - ) ]
>> author of REBOL: THE OFFICIAL GUIDE
>> REBOL Press: The Official Source for REBOL Books
>> http://www.REBOLpress.com
>> visit me at http://www.TechScribe.com
>>
>
;- Elan [ : - ) ]
author of REBOL: THE OFFICIAL GUIDE
REBOL Press: The Official Source for REBOL Books
http://www.REBOLpress.com
visit me at http://www.TechScribe.com