rust_lisp/model/
lambda.rs

1use std::cell::RefCell;
2use std::fmt::Debug;
3use std::rc::Rc;
4
5use super::{Env, Symbol, Value};
6
7/// A Lisp function defined in Lisp.
8#[derive(Debug, Clone)]
9pub struct Lambda {
10    pub closure: Rc<RefCell<Env>>,
11    pub argnames: Vec<Symbol>,
12    pub body: Rc<Value>,
13}
14
15impl PartialEq for Lambda {
16    fn eq(&self, other: &Self) -> bool {
17        self.closure.as_ptr() == other.closure.as_ptr()
18            && self.argnames == other.argnames
19            && self.body == other.body
20    }
21}
22
23impl std::hash::Hash for Lambda {
24    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
25        self.closure.as_ptr().hash(state);
26        self.argnames.hash(state);
27        self.body.hash(state);
28    }
29}
30
31impl std::fmt::Display for Lambda {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        let body_str = format!("{}", &self.body);
34
35        return write!(
36            f,
37            "({}) {}",
38            self.argnames
39                .iter()
40                .map(|sym| sym.0.as_str())
41                .collect::<Vec<&str>>()
42                .join(" "),
43            &body_str[1..body_str.chars().count() - 1]
44        );
45    }
46}