1use lambda_calculus::Term;
2pub fn le(a: usize) -> Box<dyn Iterator<Item = bool>>{
3 if a == 0{
4 return Box::new([true,false].into_iter());
5 }
6 let len = usize::BITS - a.leading_zeros();
7 let x = if len == 1{
8 vec![]
9 }else{
10 (0..len - 2).rev().map(|a|1 << a).map(|v|a & v != 0).collect()
11 };
12 return Box::new([true].into_iter().chain(le((len - 1) as usize)).chain(x.into_iter()));
13}
14pub fn encode(t: &Term) -> Box<dyn Iterator<Item = bool> + '_>{
15 match t{
16 Term::Var(v) => le(*v),
17 Term::Abs(term) => Box::new([false,false].into_iter().chain(encode(&*term))),
18 Term::App(t) => {
19 let (a,b) = t.as_ref();
20 Box::new([false,true].into_iter().chain(encode(a)).chain(encode(b)))
21 },
22 }
23}
24pub fn ld(a: &mut impl Iterator<Item = bool>) -> Option<usize>{
25 if !a.next()?{
26 return Some(0);
27 }
28 let mut x = 1;
29 let l = ld(a)?;
30 for _ in (0..l).rev(){
31 x = 2 * x + (if a.next()?{
32 1
33 }else{
34 0
35 })
36 };
37 return Some(x);;
38}
39pub fn decode(a: &mut impl Iterator<Item = bool>) -> Option<Term>{
40 match a.next()?{
41 true => Some(Term::Var(ld(a)?)),
42 false => match a.next()?{
43 false => Some(Term::Abs(Box::new(decode(a)?))),
44 true => Some(Term::App(Box::new((
45 decode(a)?,
46 decode(a)?
47 ))))
48 }
49 }
50}