自然数的构建
对于lisp语言来说,抽象与应用是最基本的,而对于像C++这样的控制性语言,条带与位置应该我觉得也是蛮基本的,试试构造自然数?
#include <vector> using namespace std; template<typename T> struct Nature { private: typename T::iterator iter; T * tape; public: static Nature zero(T& tape_){ Nature x; x.tape = &tape_; x.iter = tape_.begin(); return x; } Nature succ(){ Nature x; x.tape = tape; x.iter= iter; x.iter++; return x; } Nature pred(){ Nature x; x.tape = tape; x.iter= iter; x.iter--; return x; } bool operator ==(Nature n) { return iter == n.iter; } bool operator !=( Nature n) { return !(iter == n.iter); } Nature operator +(Nature n){ Nature zero = Nature::zero(*n.tape); Nature x = *this; while(n != zero) { x = x.succ(); n = n.pred(); } return x; } Nature operator *(Nature n){ Nature one = Nature::zero(*n.tape).succ(); Nature x = *this; while(n != one) { x = x + *this; n = n.pred(); } return x; } static Nature what(T & _tape,typename T::iterator _iter ) { Nature zero = Nature::zero(_tape); Nature x = zero; while(zero.iter!=_iter) { _iter--; x = x.succ(); } return x; } void show() { Nature zero = Nature::zero(*tape); Nature x = zero; T::iterator it = iter; if(zero.iter == it)printf("_"); while(zero.iter != it) { printf("0"); it--; x = x.succ(); } } }; int test_nature() { typedef vector<char> Tape; Tape tape(1000); Nature<Tape> zero = Nature<Tape>::zero(tape); Nature<Tape> one = zero.succ(); Nature<Tape> two = zero.succ().succ(); Nature<Tape> three = zero.succ().succ().succ(); Nature<Tape> four = zero.succ().succ().succ().succ(); printf("\r\n four is: "); four.show(); Nature<Tape> y = four * three; printf("\r\n y is %"); y.show(); return 1; }