aboutsummaryrefslogtreecommitdiff
path: root/src/sexp/step.rs
blob: 0989ee3381fdb19e0e22d116571dc35159861d26 (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

use crate::sexp::{SExp, SExp::*, SLeaf::*, util::*};

impl SExp {

    /// Evaluates the s-expression one step.
    ///
    /// **Integer operations**
    ///
    /// Addition, subtraction, multiplication and division
    /// are supported.
    /// ```rust
    /// use melisp::sexp::{SExp::*, SLeaf::*, util::*};
    ///
    /// assert_eq!(
    ///     scons(Add, scons(1, scons(1, Nil))).step(),
    ///     Ok(Atom(Int(2)))
    /// );
    ///
    /// assert_eq!(
    ///     scons(Sub, scons(1, scons(2, Nil))).step(),
    ///     Ok(Atom(Int(-1)))
    /// );
    ///
    /// assert_eq!(
    ///     scons(Mul, scons(2, scons(3, Nil))).step(),
    ///     Ok(Atom(Int(6)))
    /// );
    ///
    /// assert_eq!(
    ///     scons(Div, scons(6, scons(2, Nil))).step(),
    ///     Ok(Atom(Int(3)))
    /// );
    /// ```
    ///
    /// Division truncates the decimals.
    /// ```rust
    /// use melisp::sexp::{SExp::*, SLeaf::*, util::*};
    ///
    /// assert_eq!(
    ///     scons(Div, scons(5, scons(2, Nil))).step(),
    ///     Ok(Atom(Int(2)))
    /// );
    /// ```
    ///
    /// Also, addition and multiplication can take more than two arguments:
    /// ```rust
    /// use melisp::sexp::{SExp::*, SLeaf::*, util::*};
    ///
    /// assert_eq!(
    ///     scons(Add, scons(1, scons(2, scons(3, Nil)))).step(),
    ///     Ok(Atom(Int(6)))
    /// );
    ///
    /// assert_eq!(
    ///     scons(Mul, scons(1, scons(2, scons(3, Nil)))).step(),
    ///     Ok(Atom(Int(6)))
    /// );
    /// ```
    ///
    /// Here's an example of a bit more complicated expression
    /// from wikipedias article on s-expressions.
    /// ```rust
    /// use melisp::sexp::{SExp::*, SLeaf::*, util::*};
    ///
    /// fn main() {
    ///     let exp = scons(
    ///         Mul,
    ///         scons(
    ///             2,
    ///             scons(
    ///                 scons(Add, scons(3, scons(4, Nil))),
    ///                 Nil
    ///             )
    ///         )
    ///     );
    ///
    ///     let exp = exp.step().unwrap();
    ///     assert_eq!(exp, scons(Mul, scons(2, scons(7, Nil))));
    ///
    ///     let exp = exp.step().unwrap();
    ///     assert_eq!(exp, Atom(Int(14)));
    /// }
    ///
    /// ```
    pub fn step(self) -> Result<Self, String> {
        match self {

            // List processing

            //     op not a value
            // -----------------------
            // (op x) -> (op.step() x)
            SCons(op, l) if !(*op).is_value() => Ok(scons(op.step()?, l)),


            // op value and a1 .. an values, and b0, b1 .. bn not values
            // ---------------------------------------------------------
            //   (op a1 ... an b) -> (op a1 ... an b0.step() b1 .. bn)
            SCons(op, l) if !(*l).consists_of_values() => {
                fn inner(s: SExp) -> Result<SExp, String> {
                    match s {
                        SCons(a, b) if (*a).is_value() => Ok(scons(a, inner(*b)?)),
                        SCons(a, b) => Ok(scons(a.step()?, b)),
                        x => x.step()
                    }
                }
                Ok(scons(op, inner(*l)?))
            },


            // Arithmetic


            //      t1, ..., tn integers
            // ------------------------------
            // (+ t1 ... tn) -> t1 + ... + tn
            SCons(op, l) if *op == Atom(Add) => l.into_vec()?
                .iter()
                .fold(
                    Ok(0),
                    |acc, el| {
                        match el {
                            Int(x) => acc.map(|v| x+v),
                            _ => Err(
                                "'+' should only be given integers".to_string()
                                )
                        }
                    }
                ).map(|x| Atom(Int(x))),


            //      t1, ..., tn integers
            // ------------------------------
            // (* t1 ... tn) -> t1 * ... * tn
            SCons(op, l) if *op == Atom(Mul) => l.into_vec()?
                .iter()
                .fold(
                    Ok(1),
                    |acc, el| {
                        match el {
                            Int(x) => acc.map(|v| x*v),
                            _ => Err(
                                format!("'*' should only be given integers, found {:?}", el)
                                )
                        }
                    }
                ).map(|x| Atom(Int(x))),


            //    t1,t2 integers
            // --------------------
            // (- t1 t2) -> t1 - t2
            SCons(op, l) if *op == Atom(Sub) => {
                let ls = l.into_vec()?;
                if ls.len() == 2 {
                    match (ls[0].clone(), ls[1].clone()) {
                        (Int(a), Int(b)) => Ok(Atom(Int(a - b))),
                        _ => Err("'-' should be only given integers".to_string())
                    }
                } else {
                    Err(format!("'-' should be given 2 arguments, found {}", ls.len()))
                }
            },


            //    t1,t2 integers
            // --------------------
            // (/ t1 t2) -> t1 / t2
            SCons(op, l) if *op == Atom(Div) => {
                let ls = l.into_vec()?;
                if ls.len() == 2 {
                    match (ls[0].clone(), ls[1].clone()) {
                        (_, Int(0)) => Err("division by zero".to_string()),
                        (Int(a), Int(b)) => Ok(Atom(Int(a / b))),
                        _ => Err("'/' should be only given integers".to_string())
                    }
                } else {
                    Err(format!("'/' should be given 2 arguments, found {}", ls.len()))
                }
            },

            // t is value
            // ----------
            //   t -> t
            t if t.is_value() => Ok(t),

            t => Err(format!("unimplemented: {:?}.step()", t)),
        }
    }
}