2012-08-08

SCIP in C++11 ― 2.2.1節 その4


リストの写像と問題2.23

mapSTLコンテナ名だから、ここではmappingにする。
algorithmgenerateに似ているが、入出力リストの型を選ばない分、より一般的だな。
問題2.212.22はあまり興味ないのでパス。


----
// map
// map for single input list
template <typename ArgType, typename ReturnType>
const List mapping
(const function<ReturnType(ArgType)>& procedure,
 const List& listTree)
{  
    if(isNull(listTree)){return(makeList());}
    return(cons(procedure(value<ArgType>(car(listTree))),
                mapping(procedure,cdr(listTree))));
}

// for-each
template <typename ArgType>
void forEach(const function<void(ArgType)>& procedure,
             const List& listTree)
{
    if(isNull(listTree)){return;}
    procedure(value<ArgType>(car(listTree)));
    forEach(procedure, cdr(listTree));
}

//---------abstraction barrier---------
// scaling
template <typename FactorType>
const List scaleList
(const List& listTree, const FactorType& factor)
{
    function<FactorType(FactorType)> factoring
        =[factor](const FactorType& x){return(x*factor);};
    return(mapping(factoring,listTree));
}


int main(int argc, char** argv)
{
    const function<double(double)> absolute
        =[](const double x){return(abs(x));};
    auto list1(mapping(absolute,makeList(-10.0,2.5,-11.6,17.0)));
    cout<<"(map abs (list -10 2.5 -11.6 17)) = "
        <<listString(list1)<<endl;
   
    const function<int(int)> square=[](const int x){return(x*x);};
    auto list2(mapping(square,makeList(1,2,3,4)));
    cout<<"(map (lambda (x) (* x x))) (list 1 2 3 4) = "
        <<listString(list2)<<endl;

    auto list3(scaleList(list2,3));
    cout<<"(scale-list (list 1 4 9 16) 3) = "
        <<listString(list3)<<endl;

    cout<<endl<<"Excersize 2.23:"<<endl;
    cout<<"(for-each (lambda(x)(newline)(display x))"<<endl;
    cout<<"  (list 57 321 88)"<<endl;
    function<void(List)> display
        =[](const List& x){cout<<value<string>(x)<<endl;};
    forEach(display,makeList(57,321,88));
   
    return(0);
}
----
出力
----
(map abs (list -10 2.5 -11.6 17)) = (10 2.5 11.6 17)
(map (lambda (x) (* x x))) (list 1 2 3 4) = (1 4 9 16)
(scale-list (list 1 4 9 16) 3) = (3 12 27 48)

Excersize 2.23:
(for-each (lambda(x)(newline)(display x))
  (list 57 321 88)
57
321
88

0 件のコメント :

コメントを投稿