Skip to content

Commit 8255c6e

Browse files
test: added y_combinator test (#131)
* test: added `y_combinator` test * fix: formatting
1 parent 28498af commit 8255c6e

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

tests/cpl/y_combinator/test.cpp

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// Copyright (c) Brandon Pacewic
2+
// SPDX-License-Identifier: MIT
3+
4+
#include <cassert>
5+
#include <vector>
6+
7+
#include "xutility.h"
8+
9+
int main() {
10+
using namespace cpl;
11+
{
12+
auto factorial = y_combinator([](auto self, int n) -> int { return n <= 1 ? 1 : n * self(n - 1); });
13+
14+
assert(factorial(0) == 1);
15+
assert(factorial(1) == 1);
16+
assert(factorial(5) == 120);
17+
assert(factorial(10) == 3628800);
18+
}
19+
{
20+
auto gcd = y_combinator([](auto self, int a, int b) -> int { return b == 0 ? a : self(b, a % b); });
21+
22+
assert(gcd(20, 30) == 10);
23+
assert(gcd(48, 18) == 6);
24+
assert(gcd(0, 5) == 5);
25+
assert(gcd(17, 13) == 1);
26+
}
27+
{
28+
auto fib = y_combinator([](auto self, int n) -> int { return n <= 1 ? n : self(n - 1) + self(n - 2); });
29+
30+
assert(fib(0) == 0);
31+
assert(fib(1) == 1);
32+
assert(fib(10) == 55);
33+
assert(fib(15) == 610);
34+
}
35+
{
36+
std::vector<std::vector<int>> adj = {{1, 2}, {3, 4}, {}, {}, {}};
37+
std::vector<int> visited;
38+
39+
auto dfs = y_combinator([&](auto self, int node) -> void {
40+
visited.push_back(node);
41+
for (int next : adj[node]) {
42+
self(next);
43+
}
44+
});
45+
46+
dfs(0);
47+
assert(visited.size() == 5);
48+
assert(visited[0] == 0);
49+
assert(visited[1] == 1);
50+
assert(visited[2] == 3);
51+
assert(visited[3] == 4);
52+
assert(visited[4] == 2);
53+
}
54+
{
55+
int call_count = 0;
56+
auto counter = y_combinator([&](auto self, int n) -> int {
57+
++call_count;
58+
return n <= 0 ? 0 : self(n - 1);
59+
});
60+
61+
counter(5);
62+
assert(call_count == 6);
63+
}
64+
65+
return 0;
66+
}

0 commit comments

Comments
 (0)