diff --git a/content/Rustでの評価文脈(環境)のRAIIっぽい実装.md b/content/Rustでの評価文脈(環境)のRAIIっぽい実装.md index 7bd5307e..df41f1ba 100644 --- a/content/Rustでの評価文脈(環境)のRAIIっぽい実装.md +++ b/content/Rustでの評価文脈(環境)のRAIIっぽい実装.md @@ -20,14 +20,28 @@ fn eval<'a>(expr:Expr,env:&'a mut Vec<(String,Val)>)->Result{ Environmentは評価全体で見ればLetやLambdaごとに分岐していく構造だけれど、局所的には1列のベクタで表現できる +こんな感じすかねえ + ```rust -struct<'a,T> Environment(&'a mut Vec) - -impl<'a,T> Environment{ - pub fn new()->Self{ - Self(&mut Vec::new()) - } +struct EnvironmentT<'a, T>(&'a mut Vec<(String, T)>, usize); +impl<'a, T> EnvironmentT<'a, T> { + pub fn new(vec: &'a mut Vec<(String, T)>, mut names: Vec<(String, T)>) -> Self { + let len = vec.len(); + vec.append(&mut names); + Self(vec, len) + } + pub fn drop(&mut self) { + self.0.truncate(self.1); + } + pub fn lookup(&self, name: &String) -> Option<&'a T> { + let res = self + .0 + .iter() + .rev() + .filter(|(n, _v)| name == n) + .collect::>(); + res.get(0).map(|(_, v)| v) + } } - ``` \ No newline at end of file