Hash! vector! and map!



I think these are special datatypes that deserve a special chapter for them. They may improve the quality and speed of your work considerably.

Hash! and vector! are high performance series, i.e., they are faster when dealing with large sets.

I suggest you take a look at the Blocks & Series chapters before studying this.

 hash!  Red-by-example

hash! is a series that is "hashed" to make searches faster. Since "hashing" consumes resources, it is not worth creating  a hash!  for a series that will be searched just a few times. However, if your series will be constantly searched, consider making it a hash! . Rebol website claims searches may be 650 times faster than on a regular series.


>> a: make hash! [a 33 b 44 c 52]
== make hash! [a 33 b 44 c 52]

>> select a [c]
== 52

>> select a 'c
== 52

>> a/b
== 44

Nothing new really, it's just a series.


vector!  Red-by-example

Vectors are high performance series of integer! ,float!char! or percent!

To create a vector you must use make vector!

While hash! allow you to perform searches faster,  vector! allows faster math operations as they can be performed on the entire series at once.


>> a: make vector! [33 44 52]
== make vector! [33 44 52]

>> print a
33 44 52

>> print a * 8
264 352 416


Notice that you could not do that on a regular series:


>> a: [2 3 4 5]

== [2 3 4 5]

>> print a * 2

*** Script Error: * does not allow block! for its value1 argument

*** Where: *

*** Stack:  


 map! action! put   Red documentation  Red-by-example

Maps are high performance dictionaries that associate keys with values (key1: val1  key2: val2 ... key3: val3).

Maps are not series. You can't use most of series' built-in functions (commands) on them.

To set and retrieve values from the dictionary we use select (from series) and a a special action: put.

>> a: make map! ["mini" 33 "winny" 44 "mo" 55]
== #(
       "mini" 33
       "winny" 44
       "mo" 55
...

>> print a
"mini" 33
"winny" 44
"mo" 55

>> print select a "winny"
44

>> put a "winny" 99
== 99

>> print a
"mini" 33
"winny" 99
"mo" 55

How to  native! extend a map!

Since map! is not a series and so you can't use things like append, poke or insert, how do you add new items to it? The answer is the built-in function extend.

>> a: make map! ["mini" 33 "winny" 44 "mo" 55]

== #(

   "mini" 33

   "winny" 44

   "mo" 55

)


>> extend a ["more" 23 "even more" 77]


  ...


>> probe a

#(

   "mini" 33

   "winny" 44

   "mo" 55

   "more" 23

   "even more" 77

)

  ...



< Previous topic                                                                                          Next topic >