1.1 3) Write a recursive program to do the following. Having a complex list input such as : (1 (2 3) (4)), replace every "4" in the list with "8", the above list will become: (1 (2 3) (8))
Solution
We show how to do the simple list
first. Here is the pseudo code:
repl(a)
1: if a == nil then ret nil
2: if head(a) == 4 then ret cons(8, repl(tail(a))
3: ret cons(head(a), repl(tail(a))
Now we will tackle the complex list, must handle the case head(a) is a list.
repl2(a)
1: if a == nil then ret nil
2: if isatom(head(a))
3: if head(a) == 4 then ret cons(8,
repl2(tail(a))
4: else ret cons(head(a), repl2(tail(a))
5: ret cons(repl2(a), repl2(tail(a))
line 1: terminate case
// test atom equality
int eqatom(int a,int b){
return (head(a) == head(b)) && (tail(a) == tail(b));
}
// replace with complex list
int repl2(int a){
if( a == NIL ) return NIL;
if( isatom(head(a)) ){
if( eqatom(head(a),number(4)) ) return
cons(number(8),repl2(tail(a)));
else return cons(head(a), repl2(tail(a)));
}else
return cons(repl2(head(a)), repl2(tail(a)));
}
1-2 3) Write a recursive program to do the following. Having a complex list input such as : (1 (2 3) (4)), reverse the list, the above list will be : ((4) (3 2) 1)
Do the simple list first. Use a second function to hold "accumulating parameter" ( revs(a,b) ). Here is the pseudo code:rev(a)
revs(a,NIL)
revs(a,b)
if a == NIL then ret b
ret cons(head(a), revs(tail(a),b))
rev2(a)
revs2(a,NIL)
revs2(a,b)
if a == NIL then ret b
if isatom(head(a)) then ret cons(head(a), revs2(tail(a),b))
ret cons(revs2(head(a),NIL), revs2(tail(a),b))
// reverse complex list
int revs2(int a, int b){
if( a == NIL ) return b;
if( isatom(head(a)) ) return revs2(tail(a), cons(head(a),b));
return revs2(tail(a), cons(revs2(head(a),NIL), b));
}
int rev2(int a){
return revs2(a, NIL);
}
last update 19 Sept 2018