6.36. kink/container/TREE_MAP

Provides an `order_map` implementation which stores keys in a balanced binary tree.

Tree map is a safe default choice, because it guarantees logarithmic worst-case computational complexity for operations like `get` and `set`.

6.36.1. TREE_MAP.new(...[$config={}])

`new` returns a new empty tree `order_map`.

Config method

C.order($up_to?): default = {(:X :Y) X <= Y }

Total order relation of keys

$up_to? must be a function which takes two args X and Y. `up_to?(X Y)` must return the bool value of `X up-to Y`, where `up-to` is the total order relation of keys.

Precondition

$up_to? must be a function which takes two values and returns a `bool`.

Example: default order

:TREE_MAP.require_from('kink/container/')

:Map <- TREE_MAP.new
Map.set('one' 1)
Map.set('two' 2)
Map.set('three' 3)
Map.set('four' 4)
stdout.print_line(Map.get_opt('one').repr)  # => [1]
stdout.print_line(Map.get_opt('two').repr)  # => [2]
stdout.print_line(Map.get_opt('TWO').repr)  # => []

Example: custom order

:TREE_MAP.require_from('kink/container/')

:Map <- TREE_MAP.new{(:C)
  C.order{(:X :Y)
    X.ascii_downcase <= Y.ascii_downcase
  }
}
Map.set('one' 1)
Map.set('two' 2)
Map.set('three' 3)
Map.set('four' 4)
stdout.print_line(Map.get_opt('one').repr)  # => [1]
stdout.print_line(Map.get_opt('two').repr)  # => [2]
stdout.print_line(Map.get_opt('TWO').repr)  # => [2]

6.36.2. TREE_MAP.of(...[K0 V0 K1 V1 ,,,])

`of` makes a new tree `order_map` which contains the given keys and values. Keys are ordered by `<=` operator, or `op_le` method.

The result map has key-value pairs (K0, V0), (K1, V1), (K2, V2) ,,,.

Precondition

`K0`, `K1`, `K2` ,,, must be in the domain of keys.

Example

:TREE_MAP.require_from('kink/container/')

:Map <- TREE_MAP.of('one' 1 'two' 2 'three' 3 'four' 4)
Map.pair_iter.each{([:K :V])
  stdout.print_line('{} => {}'.format(K.repr V.repr))
}
# Output:
#   "four" => 4
#   "one" => 1
#   "three" => 3
#   "two" => 2