summaryrefslogtreecommitdiff
path: root/rust/src/lambda.rs
blob: ccb8c28f049b58574274f9731ef7bc8bc03b5073 (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
use std::{
    fmt::{self, Display},
    fs::read_to_string,
};

pub fn run(arg: &str) -> String {
    let content = read_to_string(arg).unwrap();
    let result = interpret(&content.to_string());

    result.to_string()
}

#[derive(Debug, PartialEq)]
pub enum Value {
    Num(i32),
    Bool(bool),
    Sym(String),
}

impl Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Num(i) => write!(f, "{}", i),
            Value::Bool(b) => write!(f, "{}", b),
            Value::Sym(s) => write!(f, "{}", s),
        }
    }
}

fn interpret(arg: &str) -> Value {
    arg.parse::<i32>()
        .map(Value::Num)
        .or(arg.parse::<bool>().map(Value::Bool))
        .unwrap_or(Value::Sym(arg.to_string()))
}

#[cfg(test)]
mod tests {
    use super::interpret;
    use super::Value::*;
    use proptest::prelude::*;

    proptest! {
            #[test]
            fn interpret_integer_as_number(i in -1000i32..1000) {
                let result = interpret(&i.to_string());
                assert_eq!(Num(i), result);
            }

    }

    #[test]
    fn interpret_truth_values_as_booleans() {
        assert_eq!(Bool(true), interpret("true"));
        assert_eq!(Bool(false), interpret("false"));
    }

    #[test]
    fn interpret_identifiers_values_as_symbols() {
        assert_eq!(Sym("foo".to_string()), interpret("foo"));
    }
}