CSE 413

Quiz #6 with answers

5/21/97

Two points per part except as noted.

0. The Lisp function 'max' returns the maximum numeric value in a list, or null if its argument is not a list or is a list without numbers in it. Examples:

(max '(10 109 D 7)) returns 109

(max 'sam) returns nil

a. Recast this in terms of Prolog (this part of your answer contains only an English description, no actual Prolog syntax).

A predicate which is true if its first argument is a list and its second argument is the value of the largest number in that list. (Could reverse the two arguments, of course.)

 b. Using your answer to part a, restate the two LISP examples above in Prolog.

max ([10,109,d,7],X)? X=109 yes

max (sam, X)? no

 1. Write a Prolog predicate 'startsalike' which returns true if and only if its argument is a list whose first two elements are the same. For full credit, write this as a single fact (nothing on the right-hand side) with no unused variables.

 startsalike([H,H|_]).

2. Write a Prolog predicate 'findalike' with two arguments. The first argument is a list. If the list contains two consecutive identical elements, then the predicate is true if and only if the second argument is equal to this repeated element. If there is more than one repeated element, the second argument should be the earliest such value. Examples:

findalike([1,2,3,4,5],X)? no

findalike([1,2,2,3,4,5],Y)? Y=2 yes

findalike([1,2,3,2,4,5],Y)? no

findalike([1,3,3,4,5,5,5,6,6],X)? X=3 yes

findalike([a,s,[1,2,k],[1,2,k],z],W)? W=[1,2,k] yes

findalike([H,H|_],H) :- !.

findalike([_|T],H) :- findalike(T,H).

No points off (this time) for not using a cut or not using anonymous variables where possible, or for not doing as much matching as possible on the left-hand side. But those are important for developing a feel for the language, so you should use them in your homework and on the final exam.