prolog代写 159.202 Declarative Programming

Student Name Student ID Mark

___________________________ ___________________________ ___/30

159.202 Declarative Programming Semester 2 2016

Mid-Semester Test Time allowed: 50 minutes

Attempt ALL questions.

The test is worth 30 marks.
This represents 30% of your final mark.

Answer each question in the space provided.

1

Question 1 – Short Answer Questions [10 marks] (Write your answers in the space provided)

A. What are the three matching or unification rules in Prolog? [3 marks]

B. Given the following database and query, what will the result from Prolog be?
[2 marks]

plays(john, golf).
plays(pete, golf),
plays(mary, tennis).
likes(john, X) :- plays(X, golf).

?- likes(john, X).

C. Describe the two cases of a recursive function.

[1 mark]

D. Why does arithmetic introduce problems into Prolog?

[1 mark]

Page 2 of 6

E. What does the cut operator do? Explain the difference between a red cut and a green cut. [2 marks]

F. What is the closed-world assumption and how does it affect negation in Prolog? [1 mark]

Question 2 – Prolog Programming [20 marks] (Write your answers in the space provided)

A. Write a predicate to count the number of times an element appears in a list. It

should have the form:

[4 marks]

count(Element, List, Number)

Page 3 of 6

B. Write a Prolog predicate to calculate the nth value in the sequence defined by the following recurrence relation. The sequence starts with F(0) = 0.9 and the first five values of the sequence are (0.9, 0.18, 0.295, 0.416, 0.486) to 3 d.p. [4 marks]

F(n) = 2×F(n-1) × (1 – F(n-1))

C. Modify your predicate from part B to add each new number calculated to the database as a fact. Write the output from listing for your predicate after a single query for n = 4. (the rounded values from part B are sufficient). [4 marks]

Page 4 of 6

D. Write a predicate that prompts the user, reads input from them and echoes it back by writing it to the terminal, followed by whether the term evalutes to true or not. This predicate should continue to read terms and echo them until the user enters

the term stop.

?- query.
Enter term: 5 > 6.
The term: 5>6 is false.

Enter term: 11 =:= 5+6.
The term: 11=:=5+6 is true.

Enter term: stop. true.

[4 marks]

E. Write an predicate and that is true if both the first argument and the second argument are true. Define it as an operator with a precedence of 800, it should be a

left-associative operator.

[4 marks]

THE END

Page 5 of 6

Scratch Page – (Will not be marked)

Page 6 of 6