summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 31f230ea1eae0e00c967a8b48c6d27d6952a1190 (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
pub type Number = f32;

pub type Poly = Vec<Number>;

#[derive(Debug)]
pub enum Lerp {
    Node(Box<Lerp>, Box<Lerp>),
    Leaf(Number, Number)
}

impl Lerp {
    pub fn new(v: Vec<Number>) -> Box<Lerp> {
        Lerp::new_s(&v[..])
    }

    fn new_s(v: &[Number]) -> Box<Lerp> {
        match v.len() {
            0 => Box::new(Lerp::Leaf(0.0, 0.0)),
            1 => Box::new(Lerp::Leaf(v[0], v[0])),
            2 => Box::new(Lerp::Leaf(v[0], v[1])),
            _ => Box::new(Lerp::Node(Lerp::new_s(&v[0..v.len() - 1]), Lerp::new_s(&v[1..v.len()])))
        }
    }
}

pub fn lp(l: Box<Lerp>) -> Poly {
    match *l {
        Lerp::Leaf(a, b) => vec![a, b - a],
        Lerp::Node(a, b) => {
            let a = lp(a);
            let b = lp(b);
            let c = poly_sub(&b, &a);
            skewed_sum(a, c)
        }
    }
}

fn poly_sub(a: &Poly, b: &Poly) -> Poly {
    let mut r = a.clone();
    for i in 0..r.len() {
        r[i] -= b[i];
    }
    r
}

fn skewed_sum(a: Poly, b: Poly) -> Poly {
    let mut r = a.clone();
    for i in 0..r.len() - 1 {
        r[i + 1] += b[i];
    }
    r.push(b[b.len() - 1]);
    r
}