自然数的构建

  对于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;
}

 

转载于:https://www.cnblogs.com/qianxj/archive/2013/04/24/3040841.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值