Blocks as various data structures in Rebol

211 Views Asked by At

I gather that in Rebol one is expected to use a block for representing arbitrary structured data. Are there built-in or standard ways of treating blocks as data structures other than lists?

I am thinking of:

  • stacks
  • queues (possibly double-ended)
  • sets
  • maps aka. associative arrays
1

There are 1 best solutions below

3
On BEST ANSWER

Rebol have three holders of arbitrary data that all can be treated the same way.

  • block! implemented as an array, for fast index (integer) referencing
  • list! implemented as a linked list, for fast inserting and removing data
  • hash! implemented as a hash referenced list, for fast lookup of both data and key

You operate on them in the same way with

insert append index? find poke select ...

but they differ a little in result and particularly in response time.

In your case use

  • block! for a stack
  • list! for queues (I think)
  • hash! for associative arrays

As mentioned all operate similarly (even the hash! can be referenced by index). Hence you can treat any of them as an associative array.

>> x: [a one b two c 33]
== [a one b two c 33]
>> x/a
== one
>> x/c
== 33
>> select x 'b
== two
>> pick x 4
== two

which would result in exactly the same for a hash! defined as x: hash! [a 1 b 2 33]. So to add a new key value pair:

>> x: make hash! [ a 1 b 2 c 33]
== make hash! [a 1 b 2 c 33]
>> append x [ key value ]
== make hash! [a 1 b 2 c 33 key value]
>> x/key
== value
>> select x 'key
== value
>> pick x 8
== value

Note that rebol does not have a sense of key value pairs, the hash! is just a list of ordered values that internally will build hash! values for referencing. You can therefore just as well ask what follows the value 33 above

>> select x 33
== key

To really use it for key value pairs, use the skip refinement

>> select/skip x 33 2
== none

For the associative arrays you can also use object! in case it does not need to have dynamic fields.