Suppose that we want to make a function, and we call EXIST.
It tells us if one atom a is in one list l, it implies that the
function is going to have two parameters.
The implementation of the function can be done with some interactive control structure, but now we are going to try to do it with recursion.
The general idea will be to check if the atom is in the CAR of the
list l, otherwise check if the atom a exists in the
CDR of the list l.
Notice that here we just define the cases that we have to take care of:
CAR of the list l.
CAR of the list l and
is in the CDR of the list
Now, for each of those cases, define the solution, starting with the easy cases. Also, in each step suppose that the function can solve all the other cases, so you can use the function to define the solution of this case.
CAR of the list l.
CDR of the list l.EXIST to check if
the atom is in the CDR of the list l. The most important
part is not to forget to advance at least one step into the solution.
CDR of the list l and
is not equal to the CAR of the list l.
FUNCTION EXIST ( a , l ) =
if a = (CAR l)
Return TRUE
else
if EXIST ( a (CDR l) )
Return TRUE
else
Return FALSE.
If we implement it in LISP, the best control structure that we have
(at this point) is the COND and we are going to use it
to implement the function:
It could be the way the function come out of our mind (maybe not!) but you can factor it out in such way that we have only two cases:
CAR of the list l.
CDR of the list l.(EXIST a (CDR l)).
FUNCTION EXIST ( a , l ) =
if a = (CAR l)
Return TRUE
else
Return EXIST ( a (CDR l) )
/* that return TRUE if a EXIST in the CDR of l */
/* or FALSE otherwise */
try to implement it with this change:
First of all, define the cases:
FUNCTION DELETE ( a , l ) =
if a = (CAR l)
Return (CDR l)
else
Return (CONS a (DELETE a (CDR l)) )
Again, it is not completely well done, because it does not take care of the
null, nor does it take care of the situation when it does not receive an
atom as a parameter.
try to include that part to the function and prove it.