Monday, May 26, 2008

subst in Prolog, pt i

The assignment:
"Write subst(A,B,C,D) where list D is list C with element A substituted for all occurrences of element B."

The first case we want to handle is the base case. That is, if we have the empty list, it does not matter what A and B are, because there is nothing to replace. Therefore:
subst(A, B, [ ], [ ]).

Or, because we are using neither A nor B, we can write:
subst(_, _, [ ], [ ]).

The alternative is that we are not dealing with an empty list. In such a situation, we want to define subst recursively, such that we yank out the first element -- the head -- if it is B, and replace it with A. Unless of course the head is not element B, in which case we want to just leave it alone -- that is, put the head back on the list.

The way we pull apart such a list is as [H | T], where H is the head and T is the tail.

More on this later, but hopefully this gets you on the right track. It does not have to work exactly.

No comments: