1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
//! [Church-encoded numerals](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals)

use term::*;
use term::Term::*;
use term::Error::*;
use booleans::*;

/// Produces a Church-encoded zero.
///
/// ZERO := λfx.x = λ λ 1
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::zero;
///
/// assert_eq!(format!("{}", zero()), "λλ1");
/// ```
pub fn zero() -> Term { abs(abs(Var(1))) }

/// Applied to a Church-encoded number it produces a Church-encoded boolean, indicating whether its
/// argument is equal to zero.
///
/// IS_ZERO := λn.n (λx.FALSE) TRUE =  λ 1 (λ FALSE) TRUE
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{zero, is_zero};
/// use lambda_calculus::booleans::tru;
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(is_zero().app(zero())), tru());
/// ```
pub fn is_zero() -> Term { abs(Var(1).app(abs(fls())).app(tru())) }

/// Produces a Church-encoded one.
///
/// ONE := λfx.f x = λ λ 2 1
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::one;
///
/// assert_eq!(format!("{}", one()), "λλ21");
/// ```
pub fn one() -> Term { abs(abs(Var(2).app(Var(1)))) }

/// Applied to a Church-encoded number it produces its successor.
///
/// SUCC := λnfx.f (n f x) = λ λ λ 2 (3 2 1)
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{zero, one, succ};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(succ().app(zero())), one());
/// ```
pub fn succ() -> Term { abs(abs(abs(Var(2).app(Var(3).app(Var(2)).app(Var(1)))))) }

/// Applied to two Church-encoded numbers it produces their sum.
///
/// PLUS := λmnfx.m f (n f x) = λ λ λ λ 4 2 (3 2 1)
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{zero, one, plus};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(plus().app(zero()).app(one())), one());
/// ```
pub fn plus() -> Term { abs(abs(abs(abs(Var(4).app(Var(2)).app(Var(3).app(Var(2)).app(Var(1))))))) }

/// Applied to two Church-encoded numbers it produces their product.
///
/// MULT := λmnf.m (n f) = λ λ λ 3 (2 1)
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{one, mult};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(mult().app(one()).app(one())), one());
/// ```
pub fn mult() -> Term { abs(abs(abs(Var(3).app(Var(2).app(Var(1)))))) }

/// Applied to two Church-encoded numbers it raises the first one to the power of the second one.
///
/// POW := λbe.e b = λ λ 1 2
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{one, pow};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(pow().app(one()).app(one())), one());
/// ```
pub fn pow() -> Term { abs(abs(Var(1).app(Var(2)))) }

/// Applied to a Church-encoded number it produces its predecessor.
///
/// PRED := λnfx.n (λgh.h (g f)) (λu.x) (λu.u) = λ λ λ 3 (λ λ 1 (2 4)) (λ 2) (λ 1)
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{zero, one, pred};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(pred().app(one())), zero());
/// ```
pub fn pred() -> Term {
	abs(abs(abs(
		Var(3)
		.app(abs(abs(Var(1).app(Var(2).app(Var(4))))))
		.app(abs(Var(2)))
		.app(abs(Var(1)))
	)))
}

/// Applied to two Church-encoded numbers it subtracts the second one from the first one.
///
/// SUB := λmn.n PRED m = λ λ 1 PRED 2
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{zero, one, sub};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(sub().app(one()).app(zero())), one());
/// ```
pub fn sub() -> Term { abs(abs(Var(1).app(pred()).app(Var(2)))) }

/// Applied to two Church-encoded numbers it returns a Church-encoded boolean indicating whether its
/// first argument is less than the second one.
///
/// LT := λab.NOT (LEQ b a) = λ λ NOT (LEQ 1 2)
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{zero, one, lt};
/// use lambda_calculus::booleans::{tru, fls};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(lt().app(zero()).app(zero())), fls());
/// assert_eq!(normalize(lt().app(one()).app(one())),   fls());
/// assert_eq!(normalize(lt().app(zero()).app(one())),  tru());
/// assert_eq!(normalize(lt().app(one()).app(zero())),  fls());
/// ```
pub fn lt() -> Term { abs(abs(not().app(leq().app(Var(1)).app(Var(2))))) }

/// Applied to two Church-encoded numbers it returns a Church-encoded boolean indicating whether its
/// first argument is less than or egual to the second one.
///
/// LEQ := λmn.IS_ZERO (SUB m n) = λ λ IS_ZERO (SUB 2 1)
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{zero, one, leq};
/// use lambda_calculus::booleans::{tru, fls};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(leq().app(zero()).app(zero())), tru());
/// assert_eq!(normalize(leq().app(one()).app(one())),   tru());
/// assert_eq!(normalize(leq().app(zero()).app(one())),  tru());
/// assert_eq!(normalize(leq().app(one()).app(zero())),  fls());
/// ```
pub fn leq() -> Term { abs(abs(is_zero().app(sub().app(Var(2)).app(Var(1))))) }

/// Applied to two Church-encoded numbers it returns a Church-encoded boolean indicating whether its
/// first argument is egual to the second one.
///
/// EQ := λmn.AND (LEQ m n) (LEQ n m) = λ λ AND (LEQ 2 1) (LEQ 1 2)
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{zero, one, eq};
/// use lambda_calculus::booleans::{tru, fls};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(eq().app(zero()).app(zero())), tru());
/// assert_eq!(normalize(eq().app(one()).app(one())),   tru());
/// assert_eq!(normalize(eq().app(zero()).app(one())),  fls());
/// assert_eq!(normalize(eq().app(one()).app(zero())),  fls());
/// ```
pub fn eq() -> Term {
	abs(abs(
		and()
		.app(leq().app(Var(2)).app(Var(1)))
		.app(leq().app(Var(1)).app(Var(2)))
	))
}

/// Applied to two Church-encoded numbers it returns a Church-encoded boolean indicating whether its
/// first argument is not egual to the second one.
///
/// NEQ := λab.OR (NOT (LEQ a b)) (NOT (LEQ b a)) = λ λ OR (NOT (LEQ 2 1)) (NOT (LEQ 1 2))
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{zero, one, neq};
/// use lambda_calculus::booleans::{tru, fls};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(neq().app(zero()).app(zero())), fls());
/// assert_eq!(normalize(neq().app(one()).app(one())),   fls());
/// assert_eq!(normalize(neq().app(zero()).app(one())),  tru());
/// assert_eq!(normalize(neq().app(one()).app(zero())),  tru());
/// ```
pub fn neq() -> Term {
	abs(abs(
		or()
		.app(not().app(leq().app(Var(2)).app(Var(1))))
		.app(not().app(leq().app(Var(1)).app(Var(2))))
	))
}

/// Applied to two Church-encoded numbers it returns a Church-encoded boolean indicating whether its
/// first argument is greater than or egual to the second one.
///
/// GEQ := λab.LEQ b a = λ λ LEQ 1 2
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{zero, one, geq};
/// use lambda_calculus::booleans::{tru, fls};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(geq().app(zero()).app(zero())), tru());
/// assert_eq!(normalize(geq().app(one()).app(one())),   tru());
/// assert_eq!(normalize(geq().app(zero()).app(one())),  fls());
/// assert_eq!(normalize(geq().app(one()).app(zero())),  tru());
/// ```
pub fn geq() -> Term { abs(abs(leq().app(Var(1)).app(Var(2)))) }

/// Applied to two Church-encoded numbers it returns a Church-encoded boolean indicating whether its
/// first argument is greater than the second one.
///
/// GT := λab.NOT (LEQ a b) = λ λ NOT (LEQ 2 1)
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{zero, one, gt};
/// use lambda_calculus::booleans::{tru, fls};
/// use lambda_calculus::reduction::normalize;
///
/// assert_eq!(normalize(gt().app(zero()).app(zero())), fls());
/// assert_eq!(normalize(gt().app(one()).app(one())),   fls());
/// assert_eq!(normalize(gt().app(zero()).app(one())),  fls());
/// assert_eq!(normalize(gt().app(one()).app(zero())),  tru());
/// ```
pub fn gt() -> Term { abs(abs(not().app(leq().app(Var(2)).app(Var(1))))) }

impl Term {
	/// Returns the value of a Church-encoded number.
	///
	/// # Example
	/// ```
	/// use lambda_calculus::arithmetic::one;
	///
	/// assert_eq!(one().value(), Ok(1));
	/// ```
	pub fn value(&self) -> Result<usize, Error> {
		if let Ok(ref inner) = self.unabs_ref().and_then(|t| t.unabs_ref()) {
			Ok(try!(inner._value()))
		} else {
			Err(NotANum)
		}
	}

	fn _value(&self) -> Result<usize, Error> {
		if let Ok(ref rhs) = self.rhs_ref() {
			Ok(1 + try!(rhs._value()))
		} else if let Var(n) = *self {
			if n == 1 {
				Ok(0)
			} else {
				Err(NotANum)
			}
		} else {
			Err(NotANum)
		}
	}

	/// Checks whether a term is a Church-encoded number.
	///
	/// # Example
	/// ```
	/// use lambda_calculus::arithmetic::one;
	///
	/// assert!(one().is_number());
	/// ```
	pub fn is_number(&self) -> bool { self.value().is_ok() }
}

/// Produces a Church-encoded term with a value of the given natural number.
///
/// # Example
/// ```
/// use lambda_calculus::arithmetic::{one, to_cnum};
///
/// assert_eq!(to_cnum(1), one());
/// ```
pub fn to_cnum(n: usize) -> Term {
	let mut inner = Var(1);
	let mut count = n;

	while count > 0 {
		inner = Var(2).app(inner);
		count -= 1;
	}

	abs(abs(inner))
}

#[cfg(test)]
mod test {
	use super::*;
	use reduction::*;

	#[test]
	fn church_zero() {
		assert_eq!(normalize(is_zero().app(zero())), tru());
		assert_eq!(normalize(is_zero().app(one())), fls());
	}

	#[test]
	fn church_successor() {
		assert_eq!(normalize(succ().app(zero())), one());
		assert_eq!(normalize(succ().app(one())), abs(abs(Var(2).app(Var(2).app(Var(1))))));
		assert_eq!(normalize(succ().app(succ().app(succ().app(zero())))), abs(abs(Var(2).app(Var(2).app(Var(2).app(Var(1)))))));
	}

	#[test]
	fn church_number_identification() {
		for n in 0..5 { assert!(to_cnum(n).is_number()) }
	}

	#[test]
	fn church_number_creation() {
		assert_eq!(to_cnum(0), zero());
		assert_eq!(to_cnum(1), one());
		assert_eq!(to_cnum(2), normalize(succ().app(one())));
	}

	#[test]
	fn church_number_values() {
		for n in 0..10 { assert_eq!(to_cnum(n).value(), Ok(n)) }

		assert_eq!(tru().value(),		Err(NotANum));
		assert_eq!(Var(1).value(),		Err(NotANum));
		assert_eq!(abs(Var(1)).value(),	Err(NotANum));
	}

	#[test]
	fn church_addition() {
		assert_eq!(normalize(plus().app(one())), succ()); // PLUS 1 → SUCC

		assert_eq!(normalize(plus().app(zero()).app(zero())), zero());
		assert_eq!(normalize(plus().app(zero()).app(one())),  one());
		assert_eq!(normalize(plus().app(one()).app(zero())),  one());
		assert_eq!(normalize(plus().app(one()).app(one())),   to_cnum(2));

		assert_eq!(normalize(plus().app(to_cnum(2)).app(to_cnum(3))), to_cnum(5));
		assert_eq!(normalize(plus().app(to_cnum(4)).app(to_cnum(4))), to_cnum(8));
	}

	#[test]
	fn church_multiplication() {
		assert_eq!(normalize(mult().app(to_cnum(3)).app(to_cnum(4))), to_cnum(12));
		assert_eq!(normalize(mult().app(to_cnum(1)).app(to_cnum(3))), to_cnum(3));
		assert_eq!(normalize(mult().app(to_cnum(5)).app(to_cnum(0))), to_cnum(0));
	}

	#[test]
	fn church_exponentiation() {
		assert_eq!(normalize(pow().app(to_cnum(2)).app(to_cnum(4))), to_cnum(16));
		assert_eq!(normalize(pow().app(to_cnum(1)).app(to_cnum(6))), to_cnum(1));
		assert_eq!(normalize(pow().app(to_cnum(3)).app(to_cnum(2))), to_cnum(9));
		assert_eq!(normalize(pow().app(to_cnum(4)).app(to_cnum(1))), to_cnum(4));
//		assert_eq!(normalize(pow().app(to_cnum(5)).app(zero())),	 to_cnum(1)); // n^0 fails - why?
	}

	#[test]
	fn church_subtraction() {
		assert_eq!(normalize(sub().app(zero()).app(zero())),	zero());
		assert_eq!(normalize(sub().app(zero()).app(one())),		zero());
		assert_eq!(normalize(sub().app(one()).app(zero())),		one());
		assert_eq!(normalize(sub().app(to_cnum(2)).app(one())), one());

		assert_eq!(normalize(sub().app(to_cnum(5)).app(to_cnum(3))), to_cnum(2));
		assert_eq!(normalize(sub().app(to_cnum(8)).app(to_cnum(4))), to_cnum(4));
	}

	#[test]
	fn church_predecessor() {
		assert_eq!(normalize(pred().app(zero())), zero());
		assert_eq!(normalize(pred().app(one())), zero());
		assert_eq!(normalize(pred().app(to_cnum(5))), to_cnum(4));
	}
}