2.2.1節 並びの表現:問題2.17~2.18
tuple使ってた頃はcdrの実装でえらい苦労した部分。
Compositeパターンとshared_ptrを使ったListに変えてすっきり。
----
//
list-ref
const
List listRef(const List& listIn, const int nthElement)
{
if(0==nthElement){return(car(listIn));}
return(listRef(cdr(listIn),nthElement-1));
}
//concatenate
lists
const
List append(const List& listIn1,
const List& listIn2)
{
if(isNull(listIn1)){return(makeCopyList(listIn2));}
return(cons(car(listIn1),append(cdr(listIn1),listIn2)));
}
//
final element of a list
const
List lastPair(const List& listIn)
{return(listRef(listIn,length(listIn)-1));}
//
reverse list
const
List reverse(const List& listIn)
{
if(isNull(listIn)){return(makeList());}
return(append(reverse(cdr(listIn)),makeList(car(listIn))));
}
//---------abstraction
barrier---------
int
main(int argc, char** argv)
{
auto oneThroughFour(makeList(1,2,3,4));
cout<<"one-through-four="
<<listString(oneThroughFour)<<endl;
cout<<"(car
one-thgough-four)="
<<value<int>(car(oneThroughFour))<<endl;
cout<<"(cdr
one-through-four)="
<<listString(cdr(oneThroughFour))<<endl;
cout<<"(car (cdr
one-through-four))="
<<value<int>(cadr(oneThroughFour))<<endl;
cout<<"(cons 10
one-through-four)="
<<listString(cons(10,oneThroughFour))<<endl;
cout<<"(cons 5
one-through-four)="
<<listString(cons(5,oneThroughFour))<<endl;
auto squares(makeList(1,4,9,16));
cout<<"squares="<<listString(squares)<<endl;
cout<<"(list-ref squares
3)="<<value<int>(listRef(squares,3))<<endl;
auto odds(makeList(1,3,5,7));
cout<<"odds="<<listString(odds)<<endl;
cout<<"(length
odds)="<<length(odds)<<endl;
cout<<"(append squares
odds)="
<<listString(append(squares,odds))<<endl;
cout<<"(append odds
squares)="
<<listString(append(odds,squares))<<endl;
cout<<endl<<"Excersize
2.17:"<<endl;
auto list1(makeList(23,72,149,34));
cout<<"list1="<<listString(list1)<<endl;
cout<<"(last-pair
list1)="<<value<int>(lastPair(list1))<<endl;
cout<<endl<<"Excersize
2.18:"<<endl;
auto square2(makeList(1,4,9,16,25));
cout<<"square2="<<listString(square2)<<endl;
cout<<"(reverse
square2)="<<listString(reverse(square2))<<endl;
}
----
出力
----
one-through-four=(1
2 3 4)
(car
one-thgough-four)=1
(cdr
one-through-four)=(2 3 4)
(car
(cdr one-through-four))=2
(cons
10 one-through-four)=(10 1 2 3 4)
(cons
5 one-through-four)=(5 1 2 3 4)
squares=(1
4 9 16)
(list-ref
squares 3)=16
odds=(1
3 5 7)
(length
odds)=4
(append
squares odds)=(1 4 9 16 1 3 5 7)
(append
odds squares)=(1 3 5 7 1 4 9 16)
Excersize
2.17:
list1=(23
72 149 34)
(last-pair
list1)=34
Excersize
2.18:
square2=(1
4 9 16 25)
(reverse
square2)=(25 16 9 4 1)
0 件のコメント :
コメントを投稿