Something went wrong. Try again.
Interpreter for the i++ programming language
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483use crate::Term;use std::sync::LazyLock;
#[derive(Debug, Clone, PartialEq)]pub enum DeBruijn { Var(usize), FreeVar(String), Abs(Box<DeBruijn>), App(Box<DeBruijn>, Box<DeBruijn>),}
pub fn term_to_debruijn(term: &Term) -> DeBruijn { static S_DEBRUIJN: LazyLock<DeBruijn> = LazyLock::new(|| { let var = DeBruijn::Var; let app = |l, r| DeBruijn::App(Box::new(l), Box::new(r)); let abs = |b| DeBruijn::Abs(Box::new(b)); abs(abs(abs(app(app(var(2), var(0)), app(var(1), var(0)))))) });
static K_DEBRUIJN: LazyLock<DeBruijn> = LazyLock::new(|| DeBruijn::Abs(Box::new(DeBruijn::Abs(Box::new(DeBruijn::Var(1))))));
fn convert(term: &Term, ctx: &[String]) -> DeBruijn { match term { Term::S => S_DEBRUIJN.clone(), Term::K => K_DEBRUIJN.clone(), Term::Iota => { let s_db = S_DEBRUIJN.clone(); let k_db = K_DEBRUIJN.clone(); DeBruijn::Abs(Box::new(DeBruijn::App( Box::new(DeBruijn::App(Box::new(DeBruijn::Var(0)), Box::new(s_db))), Box::new(k_db), ))) } Term::Num(c) => DeBruijn::FreeVar(crate::format_complex(*c)), Term::Var(name) => { if let Some(idx) = ctx.iter().rev().position(|v| v == name) { DeBruijn::Var(idx) } else { DeBruijn::FreeVar(name.clone()) } } Term::App(l, r) => { let l_db = convert(l, ctx); let r_db = convert(r, ctx); DeBruijn::App(Box::new(l_db), Box::new(r_db)) } } } convert(term, &[] as &[String])}
pub fn show_lambda(term: &Term) -> String { let db = term_to_debruijn(term); debruijn_show(&db)}
fn greek(n: usize) -> String { const ALPHABET: [&str; 23] = [ "α", "β", "γ", "δ", "ε", "ζ", "η", "θ", "ι", "κ", "μ", "ν", "ξ", "ο", "π", "ρ", "σ", "τ", "υ", "φ", "χ", "ψ", "ω", ]; let base = ALPHABET[n % 23]; let primes = "'".repeat(n / 23); format!("{}{}", base, primes)}
pub fn debruijn_show(term: &DeBruijn) -> String { show_named(term, &mut Vec::new())}
fn show_named(term: &DeBruijn, names: &mut Vec<String>) -> String { match term { DeBruijn::Var(n) => { if *n < names.len() { names[names.len() - 1 - n].clone() } else { format!("{}", n) } } DeBruijn::FreeVar(name) => name.clone(), DeBruijn::Abs(body) => { let depth = names.len(); let var_name = greek(depth); names.push(var_name.clone()); let body_str = show_named(body, names); names.pop(); format!("λ{}. {}", var_name, body_str) } DeBruijn::App(l, r) => { let left = match l.as_ref() { DeBruijn::Abs(_) => format!("({})", show_named(l, names)), _ => show_named(l, names), }; let right = match r.as_ref() { DeBruijn::Abs(_) | DeBruijn::App(_, _) => format!("({})", show_named(r, names)), _ => show_named(r, names), }; format!("{} {}", left, right) } }}
pub fn beta_reduce(term: DeBruijn, max_steps: usize) -> Result<DeBruijn, crate::Error> { let mut current = term; for _ in 0..max_steps { let next = beta_step(¤t); if next == current { return Ok(current); } current = next; } Err(crate::Error::TooManyReductions( "beta reduction limit reached".to_string(), ))}
fn beta_step(term: &DeBruijn) -> DeBruijn { match term { DeBruijn::App(l, r) => match l.as_ref() { DeBruijn::Abs(body) => substitute(body, r), _ => { let l_reduced = beta_step(l); if l_reduced != **l { DeBruijn::App(Box::new(l_reduced), r.clone()) } else { let r_reduced = beta_step(r); if r_reduced != **r { DeBruijn::App(Box::new(l_reduced), Box::new(r_reduced)) } else { term.clone() } } } }, DeBruijn::Abs(body) => { let body_reduced = beta_step(body); if body_reduced != **body { DeBruijn::Abs(Box::new(body_reduced)) } else { term.clone() } } _ => term.clone(), }}
fn substitute(term: &DeBruijn, value: &DeBruijn) -> DeBruijn { fn sub(term: &DeBruijn, value: &DeBruijn, depth: usize) -> DeBruijn { match term { DeBruijn::Var(n) => { if *n == depth { shift(value, depth) } else if *n > depth { DeBruijn::Var(n - 1) } else { DeBruijn::Var(*n) } } DeBruijn::Abs(body) => DeBruijn::Abs(Box::new(sub(body, value, depth + 1))), DeBruijn::App(l, r) => { let l_sub = sub(l, value, depth); let r_sub = sub(r, value, depth); DeBruijn::App(Box::new(l_sub), Box::new(r_sub)) } DeBruijn::FreeVar(name) => DeBruijn::FreeVar(name.clone()), } } sub(term, value, 0)}
fn shift(term: &DeBruijn, amount: usize) -> DeBruijn { fn shift_inner(term: &DeBruijn, amount: usize, depth: usize) -> DeBruijn { match term { DeBruijn::Var(n) => { if *n >= depth { DeBruijn::Var(n + amount) } else { DeBruijn::Var(*n) } } DeBruijn::Abs(body) => DeBruijn::Abs(Box::new(shift_inner(body, amount, depth + 1))), DeBruijn::App(l, r) => DeBruijn::App( Box::new(shift_inner(l, amount, depth)), Box::new(shift_inner(r, amount, depth)), ), DeBruijn::FreeVar(_) => term.clone(), } } shift_inner(term, amount, 0)}
#[cfg(test)]mod tests { use super::{debruijn_show, term_to_debruijn, DeBruijn}; use crate::Term;
fn s() -> Term { Term::S } fn k() -> Term { Term::K } fn iota() -> Term { Term::Iota } fn var(s: &str) -> Term { Term::Var(s.to_string()) } fn app(l: Term, r: Term) -> Term { Term::App(Box::new(l), Box::new(r)) }
#[test] fn debruijn_k() { let term = k(); let db = term_to_debruijn(&term); let result = debruijn_show(&db); assert_eq!( result, "λα. λβ. α", "K should be λα. λβ. α, got: {}", result ); }
#[test] fn debruijn_variable() { let term = var("x"); let db = term_to_debruijn(&term); let result = debruijn_show(&db); assert!( result.contains("x"), "Variable should show as x, got: {}", result ); }
#[test] fn debruijn_s_k_k() { // S K K - direct construction, no parser let term = app(app(s(), k()), k()); let db = term_to_debruijn(&term); let result = debruijn_show(&db); // Should show as application of lambdas assert!( result.contains("λ"), "S K K should contain lambda, got: {}", result ); }
#[test] fn debruijn_k_k() { // K K let term = app(k(), k()); let db = term_to_debruijn(&term); let result = debruijn_show(&db); assert!( result.contains("λα"), "K K should contain λα binder, got: {}", result ); }
#[test] fn debruijn_variable_bound() { // In a context, variables should be bound // x in position 0 of context ["x", "y"] should be Var(1) let term = var("x"); let db = term_to_debruijn(&term); // Empty context, so x is free let result = debruijn_show(&db); assert!( result.contains("x") || result.contains("FreeVar"), "x should be free or show as FreeVar, got: {}", result ); }
#[test] fn debruijn_show_var() { // Unbound DeBruijn indices rendering let db = DeBruijn::Var(0); assert_eq!(debruijn_show(&db), "0");
let db = DeBruijn::Var(1); assert_eq!(debruijn_show(&db), "1");
let db = DeBruijn::Var(5); assert_eq!(debruijn_show(&db), "5"); }
#[test] fn debruijn_show_freevar() { let db = DeBruijn::FreeVar("x".to_string()); assert_eq!(debruijn_show(&db), "x"); }
#[test] fn debruijn_show_abs() { let db = DeBruijn::Abs(Box::new(DeBruijn::Var(0))); assert_eq!(debruijn_show(&db), "λα. α"); }
#[test] fn debruijn_show_nested_abs() { let db = DeBruijn::Abs(Box::new(DeBruijn::Abs(Box::new(DeBruijn::Var(0))))); assert_eq!(debruijn_show(&db), "λα. λβ. β"); }
#[test] fn debruijn_show_app() { let db = DeBruijn::App(Box::new(DeBruijn::Var(0)), Box::new(DeBruijn::Var(1))); assert_eq!(debruijn_show(&db), "0 1"); }
#[test] fn debruijn_show_app_with_abs_left() { let db = DeBruijn::App( Box::new(DeBruijn::Abs(Box::new(DeBruijn::Var(0)))), Box::new(DeBruijn::Var(1)), ); assert_eq!(debruijn_show(&db), "(λα. α) 1"); }
#[test] fn debruijn_show_complex() { // S combinator: λα. λβ. λγ. (α γ) (β γ) let inner1 = DeBruijn::App(Box::new(DeBruijn::Var(2)), Box::new(DeBruijn::Var(0))); let inner2 = DeBruijn::App(Box::new(DeBruijn::Var(1)), Box::new(DeBruijn::Var(0))); let body = DeBruijn::App(Box::new(inner1), Box::new(inner2)); let db = DeBruijn::Abs(Box::new(DeBruijn::Abs(Box::new(DeBruijn::Abs(Box::new( body, )))))); let result = debruijn_show(&db); assert!(result.contains("α"), "S should contain α, got: {}", result); assert!(result.contains("β"), "S should contain β, got: {}", result); assert!(result.contains("γ"), "S should contain γ, got: {}", result); }
#[test] fn debruijn_show_identity() { // K combinator: λα. λβ. α let db = DeBruijn::Abs(Box::new(DeBruijn::Abs(Box::new(DeBruijn::Var(1))))); let result = debruijn_show(&db); assert_eq!(result, "λα. λβ. α"); }
#[test] fn debruijn_show_constant() { // λα. λβ. β is constant (returns second arg) let db = DeBruijn::Abs(Box::new(DeBruijn::Abs(Box::new(DeBruijn::Var(0))))); let result = debruijn_show(&db); assert_eq!(result, "λα. λβ. β"); }
#[test] fn term_to_debruijn_preserves_structure() { // app(s, k) should become App(Abs(...), Abs(...)) let term = app(s(), k()); let db = term_to_debruijn(&term); match db { DeBruijn::App(l, r) => { assert!(matches!(*l, DeBruijn::Abs(_))); assert!(matches!(*r, DeBruijn::Abs(_))); } _ => panic!("S K should be an application"), } }
#[test] fn show_lambda_s() { let result = super::show_lambda(&s()); assert!( result.contains("λα"), "show_lambda(S) should contain λα, got: {}", result ); }
#[test] fn show_lambda_k() { let result = super::show_lambda(&k()); assert!( result.contains("λα"), "show_lambda(K) should contain λα, got: {}", result ); }
#[test] fn show_lambda_var() { let result = super::show_lambda(&var("foo")); assert!( result.contains("foo"), "show_lambda(x) should contain foo, got: {}", result ); }
#[test] fn beta_reduce_s_k_k_identity() { // S K K should reduce to identity (λα. α) let term = app(app(s(), k()), k()); let db = term_to_debruijn(&term); let reduced = super::beta_reduce(db, 100).unwrap(); let result = debruijn_show(&reduced); assert_eq!( result, "λα. α", "S K K should reduce to identity (λα. α), got: {}", result ); }
#[test] fn debruijn_iota() { let term = iota(); let db = term_to_debruijn(&term); let result = debruijn_show(&db); // ι = λf.((f S) K), should contain λ and numbers assert!( result.contains("λ"), "iota should contain lambda, got: {}", result ); }
#[test] fn debruijn_iota_iota() { // (i i) in lambda form and beta-reduced let term = app(iota(), iota()); let db = term_to_debruijn(&term); // Just check it doesn't panic or error let _ = debruijn_show(&db); }
#[test] fn debruijn_num_real() { let term = Term::Num(crate::C::new(3.14, 0.0)); let db = term_to_debruijn(&term); let result = debruijn_show(&db); assert_eq!( result, "3.14", "Real Num should show as FreeVar, got: {}", result ); }
#[test] fn debruijn_num_complex() { let term = Term::Num(crate::C::new(1.0, 2.0)); let db = term_to_debruijn(&term); let result = debruijn_show(&db); assert_eq!( result, "1.0+2.0j", "Complex Num should show as FreeVar, got: {}", result ); }
#[test] fn debruijn_num_negative_imag() { let term = Term::Num(crate::C::new(0.0, -1.0)); let db = term_to_debruijn(&term); let result = debruijn_show(&db); assert_eq!( result, "-j", "-j Num should show as FreeVar, got: {}", result ); }
#[test] fn show_lambda_num() { let term = Term::Num(crate::C::new(2.718, 0.0)); let result = super::show_lambda(&term); assert_eq!( result, "2.718", "show_lambda(Num) should be the value, got: {}", result ); }}