Vielleicht nicht die idiomatischste Implementierung, aber durchaus von einem gewissen Unterhaltungswert — Church-Numerale in C++0x:
#include <cstdlib>
#include <functional>
#include <iostream>
using namespace std;
template <typename T>
struct church {
// ----- Typen -----
typedef function<T(T)> fn;
typedef function<fn(const fn)> numeral;
// ----- Null und Nachfolger -----
static fn zero(const fn f) {
return [](T x) -> T {
return x;
};
}
static numeral succ(const numeral num) {
return [=](const fn f) -> fn {
const numeral num_ = num;
return [=](const T x) -> T {
return f(num_(f)(x));
};
};
}
// ----- Hilfsfunktionen -----
static numeral make_numeral(unsigned int n) {
numeral num = zero;
for (int i = 0; i < n; i++) {
num = succ(num);
}
return num;
}
};
// ----- Hauptprogramm -----
int twice(int n) {
return 2*n;
}
int main(int argc, char **argv) {
auto eight = church<int>::make_numeral(8);
auto ten = church<int>::succ(church<int>::succ(eight));
cout << "ten(twice)(1) = " << ten(twice)(1) << endl;
return EXIT_SUCCESS;
}
Weitere Implementierungen von Church-Numeralen gibt's bei Christoph:
Comments
Submit a comment
Note: This website uses a JavaScript-based spam prevention system. Please enable JavaScript in your browser to post comments. Comment format is plain text. Use blank lines to separate paragraphs.