Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Term::has_free_variables: check if an expression has free variables #54

Merged
merged 3 commits into from
May 30, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/term.rs
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,32 @@ impl Term {
_ => false,
}
}

/// Returns `true` if `self` has any free vairables.
///
/// # Example
/// ```
/// use lambda_calculus::*;
///
/// let with_freevar = abs(Var(2)); // λ 2
/// let without_freevar = abs(Var(1)); // λ 1
///
/// assert!(with_freevar.has_free_variables());
/// assert!(!without_freevar.has_free_variables());
pub fn has_free_variables(&self) -> bool {
self.has_free_variables_helper(0)
}

fn has_free_variables_helper(&self, depth: usize) -> bool {
match self {
Var(x) => *x > depth || *x == 0,
Abs(p) => p.has_free_variables_helper(depth + 1),
App(p_boxed) => {
let (ref f, ref a) = **p_boxed;
f.has_free_variables_helper(depth) && a.has_free_variables_helper(depth)
ljedrz marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
}

/// Wraps a `Term` in an `Abs`traction. Consumes its argument.
Expand Down Expand Up @@ -713,4 +739,11 @@ mod tests {
assert!(app(abs(Var(1)), Var(1)).is_isomorphic_to(&app(abs(Var(1)), Var(1))));
assert!(!app(abs(Var(1)), Var(1)).is_isomorphic_to(&app(Var(2), abs(Var(1)))));
}

#[test]
fn has_free_variables() {
ljedrz marked this conversation as resolved.
Show resolved Hide resolved
assert!(!(abs(Var(1)).has_free_variables()));
assert!(abs(Var(2)).has_free_variables());
assert!((Var(0)).has_free_variables());
}
}
Loading