Content deleted Content added
Mark viking (talk | contribs) Beyond start class, bumping up to C class |
|||
Line 443:
[[User:Thepigdog|Thepigdog]] ([[User talk:Thepigdog|talk]]) 03:41, 4 February 2014 (UTC)
==Another C++ example==
I don't see enough merit in having yet another C++ example. This is not a collection of different implementations of the Y combinator. See [[rosettacode.org]] for that. So I have taken it out.
If I was to be picky I would say.
* Y combinator should be templated (not int -> int).
* Dont need main (so remove iostream, cassert)
But you do all that and it still adds nothing to the understanding of the Y combinator. Sorry.
<syntaxhighlight lang="cpp">
#include <functional>
#include <iostream>
#include <cassert>
using std::function;
// Y-combinator compatible factorial
int fact(function<int(int)> f,int v)
{
if(v == 0)
return 1;
else
return v * f(v -1);
}
// Y-combinator for the int type
function<int(int)>
y(function<int(function<int(int)>,int)> f)
{
return [=](int x) {
return f(y(f), x);
};
}
int main(void)
{
function<int(int)> factorial = y(fact);
assert(y(fact)(5) == fact(y(fact), 5));
std::cout << factorial(5) << std::endl;
return 0;
}
</syntaxhighlight>
|