next up previous
Next: Recursion Up: Recursion and lists Previous: The anonymous variable

Exercises:

Rewrite the definitions of second/2 and tail/2 above to include explicit calls to the unification operator =/2.
\begin{solution}\texttt{second/2}
 
\begin{verbatim}
second([_, Second\vert _], Result):-
 Result = Second.\end{verbatim}\end{solution}
Define a predicate fifth/2 that, given a list as first argument, returns the fifth element of the list as its second argument. E.g.
|?- fifth([1,2,3,4,5,6,7], X).

X = 5

yes

\begin{solution}\texttt{fifth/2}
 
\begin{verbatim}
fifth([_, _, _, _, Five\ver...
...eater than 5, by using the 
\texttt{Head{\textbar}Tail}
notation.
\end{solution}
Recall that every list (the empty list) has both a head and a tail. Use this fact, and the headtail notation to define a predicate is_list/1 that returns true if its argument is a list (including the empty list) and false otherwise.
\begin{solution}\texttt{is\_list/1}
 
 Two clauses, one for the empty list and o...
...begin{verbatim}
is_list([ ]).
is_list([_\vert _]).\end{verbatim}
\end{solution}
Define a predicate cons/3, which takes a list as its second argument, anything as its first argument and returns as its third argument a new list in with the first argument as head and the second argument as tail.
\begin{solution}\texttt{cons/3}
 
A version with explicit unification:
\begin{ve...
...s(First, List, [First\vert List]):-
 is_list(List).\end{verbatim}
\end{solution}


Steve Harlow 2001-11-26