summary refs log tree commit diff
path: root/src/libextra/fun_treemap.rs
blob: 4461a4dba5fd4d78291181a7fc7bd6b07d1375bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*!
 * A functional key,value store that works on anything.
 *
 * This works using a binary search tree. In the first version, it's a
 * very naive algorithm, but it will probably be updated to be a
 * red-black tree or something else.
 *
 * This is copied and modified from treemap right now. It's missing a lot
 * of features.
 */


use std::cmp::{Eq, Ord};
use std::option::{Some, None};

pub type Treemap<K, V> = @TreeNode<K, V>;

enum TreeNode<K, V> {
    Empty,
    Node(@K, @V, @TreeNode<K, V>, @TreeNode<K, V>)
}

/// Create a treemap
pub fn init<K, V>() -> Treemap<K, V> { @Empty }

/// Insert a value into the map
pub fn insert<K:Eq + Ord,V>(m: Treemap<K, V>, k: K, v: V) -> Treemap<K, V> {
    @match m {
        @Empty => Node(@k, @v, @Empty, @Empty),
        @Node(kk, vv, left, right) => cond!(
            (k <  *kk) { Node(kk, vv, insert(left, k, v), right) }
            (k == *kk) { Node(kk, @v, left, right)               }
            _          { Node(kk, vv, left, insert(right, k, v)) }
        )
    }
}

/// Find a value based on the key
pub fn find<K:Eq + Ord,V:Copy>(m: Treemap<K, V>, k: K) -> Option<V> {
    match *m {
        Empty => None,
        Node(kk, v, left, right) => cond!(
            (k == *kk) { Some(copy *v)  }
            (k <  *kk) { find(left, k)  }
            _          { find(right, k) }
        )
    }
}

/// Visit all pairs in the map in order.
pub fn traverse<K, V: Copy>(m: Treemap<K, V>, f: &fn(&K, &V)) {
    match *m {
        Empty => (),
        // Previously, this had what looked like redundant
        // matches to me, so I changed it. but that may be a
        // de-optimization -- tjc
        Node(@ref k, @ref v, left, right) => {
            traverse(left, |k,v| f(k,v));
            f(k, v);
            traverse(right, |k,v| f(k,v));
        }
    }
}