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
|
use rand::Rng;
use std::collections::HashMap;
use crate::ast::*;
#[derive(Debug, PartialEq)]
pub struct Environment<'a> {
parent: Box<Option<&'a Environment<'a>>>,
bindings: HashMap<String, Value>,
}
impl<'a> Environment<'a> {
pub fn new() -> Self {
Environment {
parent: Box::new(None),
bindings: HashMap::new(),
}
}
fn bind(&mut self, var: &str, value: &Value) {
self.bindings.insert(var.to_string(), value.clone());
}
fn extends(&'a self) -> Self {
Environment {
parent: Box::new(Some(self)),
bindings: HashMap::new(),
}
}
fn lookup(&self, var: &str) -> Option<&Value> {
self.bindings.get(var).or_else(|| match *self.parent {
Some(parent) => parent.lookup(var),
None => None,
})
}
}
impl<'a> Default for Environment<'a> {
fn default() -> Self {
Self::new()
}
}
pub fn eval_all(values: &[Value]) -> Vec<Value> {
let mut env = Environment::new();
values.iter().map(|v| eval(v, &mut env)).collect()
}
pub fn eval(arg: &Value, env: &mut Environment) -> Value {
match arg {
Value::Def(var, value) => {
env.bind(var, value);
Value::Bool(true)
}
Value::Let(var, value, expr) => {
let mut newenv = env.extends();
newenv.bind(var, value);
eval(expr, &mut newenv)
}
Value::App(l, r) => match eval(l, env) {
Value::Lam(v, body) => eval(&subst(&v, &body, r), env),
Value::Sym(var) => match env.lookup(&var) {
Some(val) => eval(&Value::App(Box::new(val.clone()), r.clone()), env),
None => arg.clone(),
},
other => Value::App(Box::new(other), r.clone()),
},
Value::Sym(var) => env.lookup(var).unwrap_or(arg).clone(),
other => other.clone(),
}
}
fn subst(var: &str, body: &Value, e: &Value) -> Value {
match body {
Value::Sym(x) if x == var => e.clone(),
Value::Lam(x, b) if x == var => {
let y = gensym();
let bd = subst(x, b, &Value::Sym(y.clone()));
Value::Lam(y, Box::new(bd))
}
Value::Lam(x, b) => Value::Lam(x.to_string(), Box::new(subst(var, b, e))),
Value::App(l, r) => Value::App(Box::new(subst(var, l, e)), Box::new(subst(var, r, e))),
other => other.clone(),
}
}
fn gensym() -> String {
let mut rng = rand::thread_rng();
let n1: u8 = rng.gen();
format!("x_{}", n1)
}
#[cfg(test)]
mod lambda_test {
use crate::parser::parse;
use super::{eval, eval_all, Environment, Value};
fn parse1(string: &str) -> Value {
parse(string).pop().unwrap()
}
fn eval1(value: &Value) -> Value {
eval(value, &mut Environment::new())
}
#[test]
fn evaluating_a_non_reducible_value_yields_itself() {
let value = parse1("(foo 12)");
assert_eq!(value, eval1(&value));
}
#[test]
fn evaluating_application_on_an_abstraction_reduces_it() {
let value = parse1("((lam x x) 12)");
assert_eq!(Value::Num(12), eval1(&value));
}
#[test]
fn substitution_occurs_within_abstraction_body() {
let value = parse1("(((lam x (lam y x)) 13) 12)");
assert_eq!(Value::Num(13), eval1(&value));
}
#[test]
fn substitution_occurs_within_application_body() {
let value = parse1("(((lam x (lam y (y x))) 13) 12)");
assert_eq!(
Value::App(Box::new(Value::Num(12)), Box::new(Value::Num(13))),
eval1(&value)
);
}
#[test]
fn substitution_does_not_capture_free_variables() {
let value = parse1("(((lam x (lam x x)) 13) 12)");
assert_eq!(Value::Num(12), eval1(&value));
}
#[test]
fn interpretation_applies_to_both_sides_of_application() {
let value = parse1("((lam x x) ((lam x x) 12))");
assert_eq!(Value::Num(12), eval1(&value));
}
#[test]
fn reduction_is_applied_until_normal_form_is_reached() {
let value = parse1("((((lam y (lam x (lam y (x y)))) 13) (lam x x)) 11)");
assert_eq!(Value::Num(11), eval1(&value));
}
#[test]
fn reduction_always_select_leftmost_outermost_redex() {
// this should not terminate if we evaluate the rightmost redex first, eg.
// applicative order reduction
let value = parse1("((lam x 1) ((lam x (x x)) (lam x (x x))))");
assert_eq!(Value::Num(1), eval1(&value));
}
#[test]
fn defined_symbols_are_evaluated_to_their_definition() {
let values = parse("(def foo 12) foo");
assert_eq!(vec![Value::Bool(true), Value::Num(12)], eval_all(&values));
}
#[test]
fn let_expressions_bind_symbol_to_expression_in_environment() {
let values = parse("(let (foo (lam x x)) (foo 12))");
assert_eq!(vec![Value::Num(12)], eval_all(&values));
}
#[test]
fn let_expressions_introduce_new_scope_for_bindings() {
let values = parse("(let (foo (lam x x)) ((let (foo foo) foo) 13))");
assert_eq!(vec![Value::Num(13)], eval_all(&values));
}
#[test]
fn bound_symbol_in_higher_scope_are_resolved() {
let values = parse("(let (id (lam x x)) (let (foo 12) (id foo)))");
assert_eq!(vec![Value::Num(12)], eval_all(&values));
}
}
|