PreviousUpNext

Red-Black Trees: Float Keys; Using the red_black_map_g Generic

Mythryl provides pre-built Red-Black tree variants for only the most common key types. Float is not so honored, so to demonstrate Float key values we will need to generate our own tree variant from the underlying generic. This might sound a bit scary but is in fact ultra easy — all we have to do is provide the key type and key comparison operation and the red_black_map_g generic package does all the rest.

Warning! In general using Float values as keys is asking for trouble, because even one part in a billion accumulated floating point error on the value used as a key will be enough to make the lookup fail! In a practical situation you should probably round your Floats to Ints and use an Int-keyed tree.
    #!/usr/bin/mythryl

    package map
        =
        red_black_map_g (

            Key     =  Float;           # Type to use for keys.
            compare =  float::compare;  # How to compare two keys.
        );

    m = (map::empty: map::Map( String ));

    m = map::set (m, 0.111, "Value1");
    m = map::set (m, 0.222, "Value2");
    m = map::set (m, 0.333, "Value3");

    printf "%f -> %s\n"  0.111  (the (map::get (m, 0.111)) );
    printf "%f -> %s\n"  0.222  (the (map::get (m, 0.222)) );
    printf "%f -> %s\n"  0.333  (the (map::get (m, 0.333)) );

The run:

    linux$ ./my-script
    0.111000 -> Value1
    0.222000 -> Value2
    0.333000 -> Value3

Same script with Int values:

    #!/usr/bin/mythryl

    package map
        =
        red_black_map_g (

            Key     =  Float;           # Type to use for keys.
            compare =  float::compare;  # How to compare two keys.
        );

    m = (map::empty: map::Map( Int ));

    m = map::set (m, 0.111, 111);
    m = map::set (m, 0.222, 222);
    m = map::set (m, 0.333, 333);

    printf "%f -> %d\n"  0.111  (the (map::get (m, 0.111)) );
    printf "%f -> %d\n"  0.222  (the (map::get (m, 0.222)) );
    printf "%f -> %d\n"  0.333  (the (map::get (m, 0.333)) );

The run:

    linux$ ./my-script
    0.111000 -> 111
    0.222000 -> 222
    0.333000 -> 333

And finally with Float values:

    #!/usr/bin/mythryl

    package map
        =
        red_black_map_g (

            Key     =  Float;           # Type to use for keys.
            compare =  float::compare;  # How to compare two keys.
        );

    m = (map::empty: map::Map( Float ));

    m = map::set (m, 0.111, 0.1111);
    m = map::set (m, 0.222, 0.2222);
    m = map::set (m, 0.333, 0.3333);

    printf "%f -> %f\n"  0.111  (the (map::get (m, 0.111)) );
    printf "%f -> %f\n"  0.222  (the (map::get (m, 0.222)) );
    printf "%f -> %f\n"  0.333  (the (map::get (m, 0.333)) );

The run:

    linux$ ./my-script
    0.111000 -> 0.111100
    0.222000 -> 0.222200
    0.333000 -> 0.333300

Comments and suggestions to: bugs@mythryl.org

PreviousUpNext