문제

Church numerals can be expressed in C++0x (C++11?) using the new lambda parts of the language using something like this:

typedef function<int(int)> F;
static const F id = [=](int x) { return x; };

function<F(F)> church(unsigned int i)
{
  if(i == 0) {
    return [=] (F f) { return id; };
  }

  return [=] (F f) {
    F tmp = [=](int x) { return f(church(i-1)(f)(x)); };
    return tmp;
  };
}

Is it possible to express Church numerals using Boost.Bind and C++03? If so, how?

도움이 되었습니까?

해결책

Ok, I don't know anything about church numerals, and I haven't actually tested this code, but something like this should work :)

HTH!

// forward
boost::function<F (F)> church(unsigned int i);

typedef boost::function<int (int)> F;

int idFunc(int x)
{
  return x;
}

static const F id = boost::bind(&idFunc, _1);

F ChurchFunc0(F f)
{
  return id;
}

int ChurchFuncInner(F f, int i, int x)
{
  return f(church(i - 1)(f)(x));
}

F ChurchFunc(F f, int i)
{
  return boost::bind(&ChurchFuncInner, f, i, _1);
}

boost::function<F (F)> church(unsigned int i)
{
  if (i == 0)
  {
    return boost::bind(&ChurchFunc0, _1);
  }

  return boost::bind(&ChurchFunc, _1, i);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top