aboutsummaryrefslogtreecommitdiff
path: root/src/sexp/subst.rs
blob: abab6140a476e82f9be9260884ae8eec8e754df0 (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

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

impl SExp {
    /// Performs substitution on the s-expression.
    ///
    /// Replaces all free occurrences of variables
    /// named `name` with the given `value`
    /// in this s-expression.
    /// ```rust
    /// use melisp::sexp::{SExp::*, SLeaf::*, util::*};
    /// 
    /// assert_eq!(
    ///     scons(Add, scons(var("a"), var("b"))).subst("b", &scons(Sub, scons(2, 1))),
    ///     scons(Add, scons(var("a"), scons(Sub, scons(2, 1))))
    /// );
    /// ```
    pub fn subst(self, name: &str, value: &SExp) -> SExp {
        match self {
            SCons(a, b) => scons((*a).subst(name, value), (*b).subst(name, value)),
            Atom(Var(x)) if x == name => value.clone(),
            t => t,
        }
    }
}