cfold2 f z [] = z
cfold2 f z (x:xs) = f x z (\y -> cfold2 f y xs)
cfold f z l = cfold2 (\x t g -> f x (g t)) z l
CPS> cfold (+) 0 [1,2,3,4]
10
CPS> cfold2 (\x t g -> (x : g t)) [] [1,2,3,4]
[1,2,3,4]
CPS> cfold2 (\x t g -> g (x : t)) [] [1,2,3,4]
[4,3,2,1]
F#代码
let rec cfold2 f z = function
| [] -> z
| x::xs -> f x z (fun y -> cfold2 f y xs)
let cfold f z l = cfold2 (fun x t g -> f x (g t)) z l
> cfold (+) 0 [1;2;3;4];;
val it : int = 10
> cfold2 (fun x t g -> (x :: g t)) [] [1;2;3;4];;
val it : int list = [1; 2; 3; 4]
> cfold2 (fun x t g -> g (x :: t)) [] [1;2;3;4];;
val it : int list = [4; 3; 2; 1]
C++辅助函数
//utility.h
list<int> cons_op(int i, list<int> l)
{
l.push_front(i);
return l;
}
ostream& operator<<(ostream& os, const list<int>& l)
{
os << '[';
for(list<int>::const_iterator it = l.begin();;){
os << *it++;
if(it == l.end()) break;
os << ',';
}
return os << ']';
}
C++代码1
#include <iostream>
#include <list>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/assign.hpp>
using namespace std;
using namespace boost;
using namespace lambda;
using namespace assign;
#include "utility.h"
template<typename T, typename ActionFunc, typename U>
T cfold2(ActionFunc f, T z, const list<U>& l)
{
if(l.empty()) return z;
U x = l.front();
list<U> xs(++l.begin(), l.end());
return f(x, z, bind(static_cast<T(*)(ActionFunc,T,const list<U>&)>(&cfold2), var(f), _1, var(xs)));
}
template<typename T, typename OpFunc, typename U>
T cfold(OpFunc op, T z, const list<U>& l)
{
return cfold2(bind(op, _1, bind(_3, _2)), z, l);
}
int main()
{
list<int> l;
l += 1,2,3,4;
cout << cfold(plus<int>(), 0, l) << endl;
cout << cfold2(bind(cons_op, _1, bind(_3, _2)), list<int>(), l) << endl;
cout << cfold2(bind(_3, bind(cons_op, _1, _2)), list<int>(), l) << endl;
return 0;
}
//10
//[1,2,3,4]
//[4,3,2,1]
C++代码2
#include <array>
#include <functional>
#include <algorithm>
#include <boost/assign.hpp>
#include <iostream>
using namespace std;
using namespace boost::assign;
#include "utility.h"
template<typename T, typename ActionFunc, typename U>
T cfold2(ActionFunc f, T z, const list<U>& l)
{
if(l.empty())
return z;
U x = l.front();
list<U> xs(++l.begin(), l.end());
return f(x, z, [&](T y){return cfold2(f, y, xs);});
}
template<typename T, typename OpFunc, typename U>
T cfold(OpFunc op, T z, const list<U>& l)
{
return cfold2([&](U x, T t, function<T(T)> g){return op(x, g(t));}, z, l);
}
int main()
{
list<int> l = list_of(1)(2)(3)(4);
cout << cfold(plus<int>(), 0, l) << endl;
cout << cfold2([](int x, list<int> t, function<list<int>(list<int>)> g){return cons_op(x, g(t));}, list<int>(), l) << endl;
cout << cfold2([](int x, list<int> t, function<list<int>(list<int>)> g){return g(cons_op(x, t));}, list<int>(), l) << endl;
return 0;
}
//10
//[1,2,3,4]
//[4,3,2,1]