木の演算:問題2.35
以前、listやtupleでは挫折した問題。
今度は簡単。
----
//count-leaves
(accumulate ver.)
const
function<int(int,int)> add=
    [](const int x, const int y){return(x+y);};
const
int countLeavesAcc(const List& listTree)
{
    function<int(List)> countRecursively;
    countRecursively=[listTree]
        (const List& x)
        {
           
if(isNull(x)){return(0);}
           
if(!isPair(x)){return(1);}
           
return(countLeavesAcc(x));
        };
    return(accumulate
          
(add,0,mapping
           
(countRecursively,listTree)));
}
//---------abstraction
barrier---------
int
main(int argc, char** argv)
{
    const auto
listTree(makeList(1,makeList(2,makeList(3,4),5)));
    cout<<"t =
"<<listString(listTree)<<endl;
    cout<<"(count-leaves t) =
"<<countLeavesAcc(listTree)<<endl;
    return(0);
}
----
出力
----
t
= (1 (2 (3 4) 5))
(count-leaves
t) = 5
0 件のコメント :
コメントを投稿