rsfuzzy/
hedges.rs

1// Copyright 2015 Threat X, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8
9
10static TYPES: [&'static str; 4] = ["very", "extremely", "somewhat", "slightly"];
11
12pub fn types() -> Vec<&'static str> {
13    TYPES.iter().map(|&x| x).collect()
14}
15
16pub fn compute(hedge: &Hedge, x: f32) -> f32 {
17    hedge.compute(x)
18}
19
20#[derive(Debug, Clone)]
21pub struct Hedge {
22    hedge: Option<Box<Hedge>>,
23    p: f32
24}
25
26impl Hedge {
27    pub fn new(name: &str, hedge: Option<Box<Hedge>>) -> Hedge {
28        match name {
29            "very" => Hedge::init_very(hedge),
30            "extremely" => Hedge::init_extremely(hedge),
31            "somewhat" => Hedge::init_somewhat(hedge),
32            "slightly" => Hedge::init_slightly(hedge),
33            _ => panic!("Hedge: '{}' does not exists!", name)
34        }
35    }
36
37    fn init(hedge: Option<Box<Hedge>>, p: f32) -> Hedge {
38        Hedge {
39            hedge: hedge,
40            p: p
41        }
42    }
43   
44    fn init_very(hedge: Option<Box<Hedge>>) -> Hedge {
45        Hedge::init(hedge, 2f32)
46    }
47
48    pub fn init_extremely(hedge: Option<Box<Hedge>>) -> Hedge {
49        Hedge::init(hedge, 3f32)
50    }
51
52    pub fn init_somewhat(hedge: Option<Box<Hedge>>) -> Hedge {
53        Hedge::init(hedge, 0.5f32)
54    }
55
56    pub fn init_slightly(hedge: Option<Box<Hedge>>) -> Hedge {
57        Hedge::init(hedge, 1f32 / 3f32)
58    }
59    
60    pub fn compute(&self, x: f32) -> f32 {
61        let mut y = x;
62        if let Some(ref hedge) = self.hedge {
63            if x > 0.0 {
64                y = hedge.compute(x);
65            }
66        }
67        y.powf(self.p)
68    }
69    
70}