2012-09-26

SCIP in C++11 ― 3.1.1節その2


アキュミュレータ・呼び出しカウントと問題3.13.2

なんかうまくいってるみたいだが、右辺値参照がまだ気持ち悪い。

----
const function<List(int)> makeAccumulator(const List& stateValueIn)
{
    const List&& stateValue(std::move(stateValueIn));

    return([stateValue](const int augend){
         setInsert(stateValue+makeLeaf(augend),stateValue);
         return(stateValue);
        
     });
}


const function<List(List)> makeMonitored(const List& fIn)
{
    const List count(makeLeaf(0));
    const List&& f(std::move(fIn));

    const function<List(List)> executeF
     =[f,count](const List& argument){
     setInsert(count+makeLeaf(1),count);
     return(executable<List,List>(f)(argument));
    };
   
    const function<List(List)> callCount
     =[count](const List dummy){return(count);};

    const function<List(List)> resetCount
     =[count](const List dummy){
     setInsert(makeLeaf(0),count);
     return(count);
    };

    const function<List(List)> mf
     =[executeF,callCount,resetCount](const List& message){
     if(isNumber(message)){return(executeF(message));}
     if(isEq(message,makeLeaf("how-many-calls?")))
         {return(callCount(makeList()));}
     if(isEq(message,makeLeaf("reset-count")))
         {return(resetCount(makeList()));}
     cerr<<"Unknown request --- MAKE-MONITORED"<<endl;
     exit(1);
     return(makeList());
    };

    return(mf);
}

const function<List(List)> squareRoot
=[](const List& x){return(makeLeaf(sqrt(value<double>(x))));};


int main(int argc, char** argv)
{
    const auto A(makeAccumulator(makeLeaf(5)));

    cout<<"Excersize 3.1:"<<endl;
    cout<<"(A 10) = "<<listString(A(10))<<endl;
    cout<<"(A 10) = "<<listString(A(10))<<endl;

    cout<<endl<<"Excersize 3.2:"<<endl;
    const auto s(makeMonitored(makeLeaf(squareRoot)));
    cout<<"(s 100) = "<<listString(s(makeLeaf(100)))<<endl;
    cout<<"(s 25) = "<<listString(s(makeLeaf(25)))<<endl;
    cout<<"(s 'how-many-calls?) = "
     <<listString(s(makeLeaf("how-many-calls?")))<<endl;
    cout<<"(s 'reset-count) = "
     <<listString(s(makeLeaf("reset-count")))<<endl;
    cout<<"(s 49) = "<<listString(s(makeLeaf(49)))<<endl;
    cout<<"(s 'how-many-calls?) = "
     <<listString(s(makeLeaf("how-many-calls?")))<<endl;


    return(0);
}
----
出力
----
Excersize 3.1:
(A 10) = 15
(A 10) = 25

Excersize 3.2:
(s 100) = 10
(s 25) = 5
(s 'how-many-calls?) = 2
(s 'reset-count) = 0
(s 49) = 7
(s 'how-many-calls?) = 1

0 件のコメント :

コメントを投稿