summaryrefslogtreecommitdiff
path: root/test/peano.go
blob: 745f5153f6bcf7189af6864066ec597c12d0a8ea (plain)
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
// run

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Test that heavy recursion works. Simple torture test for
// segmented stacks: do math in unary by recursion.

package main

type Number *Number

// -------------------------------------
// Peano primitives

func zero() *Number {
	return nil
}

func is_zero(x *Number) bool {
	return x == nil
}

func add1(x *Number) *Number {
	e := new(Number)
	*e = x
	return e
}

func sub1(x *Number) *Number {
	return *x
}

func add(x, y *Number) *Number {
	if is_zero(y) {
		return x
	}

	return add(add1(x), sub1(y))
}

func mul(x, y *Number) *Number {
	if is_zero(x) || is_zero(y) {
		return zero()
	}

	return add(mul(x, sub1(y)), x)
}

func fact(n *Number) *Number {
	if is_zero(n) {
		return add1(zero())
	}

	return mul(fact(sub1(n)), n)
}

// -------------------------------------
// Helpers to generate/count Peano integers

func gen(n int) *Number {
	if n > 0 {
		return add1(gen(n - 1))
	}

	return zero()
}

func count(x *Number) int {
	if is_zero(x) {
		return 0
	}

	return count(sub1(x)) + 1
}

func check(x *Number, expected int) {
	var c = count(x)
	if c != expected {
		print("error: found ", c, "; expected ", expected, "\n")
		panic("fail")
	}
}

// -------------------------------------
// Test basic functionality

func init() {
	check(zero(), 0)
	check(add1(zero()), 1)
	check(gen(10), 10)

	check(add(gen(3), zero()), 3)
	check(add(zero(), gen(4)), 4)
	check(add(gen(3), gen(4)), 7)

	check(mul(zero(), zero()), 0)
	check(mul(gen(3), zero()), 0)
	check(mul(zero(), gen(4)), 0)
	check(mul(gen(3), add1(zero())), 3)
	check(mul(add1(zero()), gen(4)), 4)
	check(mul(gen(3), gen(4)), 12)

	check(fact(zero()), 1)
	check(fact(add1(zero())), 1)
	check(fact(gen(5)), 120)
}

// -------------------------------------
// Factorial

var results = [...]int{
	1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800,
	39916800, 479001600,
}

func main() {
	for i := 0; i <= 9; i++ {
		if f := count(fact(gen(i))); f != results[i] {
			println("FAIL:", i, "!:", f, "!=", results[i])
			panic(0)
		}
	}
}