Removing a key-value pair from a hash?
[1/3] from: stopm::mediaone::net at: 23-Feb-2002 2:44
How would one write a function to take a hash and a key, and remove the key
and the value that key is associated with from the hash? With O(1) time,
preferably.
Here's an example (let's call our function search-remove):
the-hash: make hash! ["si" "yes" "hola" "hello"]
search-remove the-hash "hola"
After this expression was complete, the-hash would have the value:
make hash! ["si" "yes"]
Alex
[2/3] from: carl:cybercraft at: 23-Feb-2002 23:08
On 23-Feb-02, Alex Liebowitz wrote:
> How would one write a function to take a hash and a key, and remove
> the key and the value that key is associated with from the hash?
<<quoted lines omitted: 5>>
> make hash! ["si" "yes"]
> Alex
I've not done anything with hash before, but treating it like a normal
block seems to work, though whether it has any unexpected effects on
the hash's index or speed I'm not sure. Others would know. Anyway,
this gives the results you asked for...
search-remove: func [a-hash [hash!] a-str [string!]][
head remove remove find a-hash a-str
]
>> the-hash: make hash! ["si" "yes" "hola" "hello"]
== make hash! ["si" "yes" "hola" "hello"]
>> search-remove the-hash "hola"
== make hash! ["si" "yes"]
>> the-hash
== make hash! ["si" "yes"]
and...
>> the-hash: make hash! ["si" "yes" "hola" "hello" "kia ora" "g'day"]
== make hash! ["si" "yes" "hola" "hello" "kia ora" "g'day"]
>> search-remove the-hash "hola"
== make hash! ["si" "yes" "kia ora" "g'day"]
>> the-hash
== make hash! ["si" "yes" "kia ora" "g'day"]
HTH.
--
Carl Read
[3/3] from: greggirwin:mindspring at: 23-Feb-2002 11:02
Hi Alex,
<< How would one write a function to take a hash and a key, and remove the
key
and the value that key is associated with from the hash? With O(1) time,
preferably. >>
remove-key-val-pair: func [hash key] [
if found? find/skip hash key 2 [
remove/part find/skip hash key 2 2
]
hash
]
I haven't tested it for performance and I don't know what FIND and REMOVE
do, internally, when operating on a hash!.
--Gregg
Notes
- Quoted lines have been omitted from some messages.
View the message alone to see the lines that have been omitted