next up previous
Next: Operators Up: Recursion and lists Previous: append/3

Exercises

Hint: in all of the following, the base involves the case where the first list argument is the empty list. Define a predicate delete/3 whose arguments are 1) a term, 2) a list and 3) another list consisting of the second argument minus the first occurrence of the term, if it occurs. For example, delete(b, [a,b,c,a,b], X) should give X = [a,c,a,b]. Note also that delete/3 should not fail; if the item to be deleted is not on the list, the original list should be returned as the value of the third argument. E.g. delete(a, [b,c,d], X) should give X = [b,c,d]
\begin{solution}
\texttt{delete\_/3}

This, like \texttt{member/2}, can be reduc...
...terimResult]):-
 delete(Item, Tail, InterimResult).\end{verbatim} \end{solution}
Define a predicate delete_all/3, like delete/3 except that the third argument is minus all occurrences of the first argument. E.g. delete_all(b, [a,b,c,a,b], X) should give X = [a,c,a]. delete_all/3 should behave like delete/3 if its first argument is not on the list.
\begin{solution}
\texttt{delete\_all/3}

This is, in fact, just like \texttt{del...
...mResult]):-
 delete_all(Item, Tail, InterimResult).\end{verbatim} \end{solution}
Define a predicate reverse/2 whose arguments are both lists, the second being the mirror image of the first. E.g. reverse([a,b,c], X) should give X=[c,b,a]. Hint: you will find it useful to use append/3 in the recursive clause of reverse/2.
\begin{solution}
\texttt{reverse/2}

The base case of this definition is that wh...
...it: reverse([a,b,c],[c,b,a]) ? 

X = [c,b,a] ? 

yes\end{verbatim}\end{solution}
Write a recursive definition that will translate a string of English words into their French (or German or Swedish or \ldots$ counterparts). You will need a set of 2-place facts giving the English and French counterparts, and a two-place recursive rule that works its way down a list, looking up the word-translations item by item, and putting the resulting translation into the second argument. The predicate should produce the following kind of result:
|?- translate(['John', is, an, idiot], French).

French = [Jean,est,un,imbecile] }

yes

\begin{solution}\texttt{translate/2}
 
We need a set of translations, coded here...
...translate_word(EH, FH),
 translate(ET, FT).\end{verbatim}\newpage
\end{solution}

next up previous
Next: Operators Up: Recursion and lists Previous: append/3
Steve Harlow 2001-11-26