[REBOL] Associative data store Re:(4)
From: allen:rebolforces at: 15-Sep-2000 8:24
This is a multi-part message in MIME format.
------=_NextPart_000_002F_01C01EEE.52DD2BD0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Digging through my own archive. I see that I wrote one last year to behave a
bit more like the collection object in VB. This also allows items to be
added and removed with an index as well, and test for existence.
I never got to thoroughly testing it though, so there are most likely many
ways to fix/improve it.
So if anyone wants to look at combining the two, you are quite welcome too.
Cheers,
Allen K
------=_NextPart_000_002F_01C01EEE.52DD2BD0
Content-Type: text/x-rebol;
name="collection.r"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
filename="collection.r"
REBOL [
Title: "Collection Object"
Author: "Allen Kamp"
Date: 11-Sep-1999
Email: [allenk--powerup--com--au]
Purpose: {To provide an object similar to the VB collection object.}
Notes: {Should make attributes and value lists read only,
Also add a method to return a paired block, for iteration,
and a clone method}
Usage: {
>> col: make collection []
>> col/set "Apple" "Green"
>> col/set "Orange" "Orange"
>> col/set "Grapes" "Purple"
>> col/count
== 3
>> col/get "Apple"
== "Green"
>> col/set "Apple" "Red"
>> col/get "Apple"
== "Red"
>> col/exists? "Apple" ;--Return the index or else false
== 1
>> col/get-item 1
== "Red"
>> col/remove "Apple"
>> col/get "Apple"
== none
;-- if you want to add to the beginning of the list
col/set/pos "Apple" "Granny Smith" 1
;-- to return the list of attributes or values
col/attributes
col/values
}
]
collection: make object! [
values: make block! [] 30
attributes: make block! [] 30
count: func [][length? attributes]
exists?: func [
attribute [any-string!]
/local mark
][
either found? mark: find attributes attribute [return (index? mark)][return false]
]
remove-all: func [][attributes: make hash! [] 30 values: make block! [] 30 exit]
remove-item: func [
key [any-string! integer!]
/local index
][
either integer? key [
index: key
][
if not index: exists? key [exit]
]
remove at attributes index
remove at values index
exit
]
get: func [
{Returns the value for the key or index. Returns none if does not exist}
key [any-string! integer!] {Attribute name string or an index}
/local index
][
if not integer? key [
either index: exists? key [
key: index
][
key: 0
]
]
return pick values key
]
set: func [
key [any-string!] {Attribute name string}
value
/pos position [integer!] {Specify a position in the list}
/local index
][
either pos [
insert at attributes position key
insert/only at values position value
exit
][
either index: exists? key [
change/only at values index value
exit
][
insert tail attributes key
insert/only tail values value
exit
]
]
]
]
------=_NextPart_000_002F_01C01EEE.52DD2BD0--