2012-08-09

SCIP in C++11 ― 2.2.2節 その3


木の写像:問題2.302.31

----
// tree-map
template<typename ReturnType, typename ArgType>
const List treeMap
(const function<ReturnType(ArgType)>& procedure,
 const List& listTree)
{
    if(isNull(listTree)){return(makeList());}
    if(!isPair(listTree)){
        return(leafMap(procedure,listTree));
    }
    return(cons(treeMap(procedure,car(listTree)),
                treeMap(procedure,cdr(listTree))));
}


//---------abstraction barrier---------
typedef int ListElementType;
typedef int FactorType;

const List scaleTree
(const List& listTree, const FactorType& factor)
{
    if(isNull(listTree)){return(makeList());}
    if(!isPair(listTree)){
        const function<FactorType(ListElementType)> factoring=
            [factor](const ListElementType x){return(factor*x);};
        return(leafMap(factoring,listTree));
    }
    return(cons(scaleTree(car(listTree),factor),
                scaleTree(cdr(listTree),factor)));
}

// for excersize 2.30
const function<ListElementType(ListElementType)>
square=[](const ListElementType x){return(x*x);};

const List squareTree_nonMap
(const List& listTree)
{
    if(isNull(listTree)){return(makeList());}
    if(!isPair(listTree)){return(leafMap(square,listTree));}
    return(cons(squareTree_nonMap(car(listTree)),
                squareTree_nonMap(cdr(listTree))));
}

// for excersize 2.31
const List squareTree(const List& tree)
{return(treeMap(square,tree));}

int main(int argc, char** argv)
{
    const auto tree1(makeList
                     (1,makeList(2,makeList(3,4),5),makeList(6,7)));
    cout<<"tree1 = "<<listString(tree1)<<endl;
    cout<<"(scale-tree tree1 10) = "
        <<listString(scaleTree(tree1,10))<<endl;

    cout<<endl<<"Excersize 2.30"<<endl;
    cout<<"(square-tree tree1) = "
        <<listString(squareTree_nonMap(tree1))<<endl;

    cout<<endl<<"Excersize 2.31"<<endl;
    cout<<"(square-tree tree1) = "
        <<listString(squareTree(tree1))<<endl;

    return(0);
}
----
出力
----
tree1 = (1 (2 (3 4) 5) (6 7))
(scale-tree tree1 10) = (10 (20 (30 40) 50) (60 70))

Excersize 2.30
(square-tree tree1) = (1 (4 (9 16) 25) (36 49))

Excersize 2.31
(square-tree tree1) = (1 (4 (9 16) 25) (36 49))

0 件のコメント :

コメントを投稿