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
74
75
76
use crate::Pattern;

pub trait Index: Ord + Copy {
    const ZERO: Self;

    fn next(self) -> Self;
}

impl Index for u8 {
    const ZERO: u8 = 0;

    fn next(self) -> u8 {
        self + 1
    }
}

impl Index for u16 {
    const ZERO: u16 = 0;

    fn next(self) -> u16 {
        self + 1
    }
}

impl Index for u32 {
    const ZERO: u32 = 0;

    fn next(self) -> u32 {
        self + 1
    }
}

impl Index for u64 {
    const ZERO: u64 = 0;

    fn next(self) -> u64 {
        self + 1
    }
}

impl Index for usize {
    const ZERO: usize = 0;

    fn next(self) -> usize {
        self + 1
    }
}

impl<F: Clone, X: Index> Pattern<F, X> {
    pub fn reindex(&self) -> Pattern<F, X> {
        // Step 1: retreive every index.
        let mut indexes = Vec::new();
        for i in self.variables() {
            indexes.push(i)
        }
        indexes.sort();

        // Step 2: create new indexes.
        let mut new_indexes = Vec::with_capacity(indexes.len());
        let mut next = X::ZERO;
        for _ in indexes.iter() {
            new_indexes.push(next);
            next = next.next();
        }

        // Step 3: replace the old indexes in the pattern.
        self.map_variables(&|x| {
            for i in 0..indexes.len() {
                if indexes[i] == x {
                    return Pattern::var(new_indexes[i]);
                }
            }
            unreachable!()
        })
    }
}