## 11.3 Exercises

Exercise 11.1

Suppose we start with an empty database. We then give the command:

`assert(q(a,b)), assertz(q(1,2)), asserta(q(foo,blug)).`

What does the database now contain?

We then give the command:

`retract(q(1,2)), assertz( (p(X) :-  h(X)) ).`

What does the database now contain?

We then give the command:

`retract(q(_,_)),fail.`

What does the database now contain?

Exercise 11.2

Suppose we have the following database:

`q(blob,blug).q(blob,blag).q(blob,blig).q(blaf,blag).q(dang,dong).q(dang,blug).q(flab,blob).`

What is Prolog's response to the queries:

1. findall(X,q(blob,X),List).

2. findall(X,q(X,blug),List).

3. findall(X,q(X,Y),List).

4. bagof(X,q(X,Y),List).

5. setof(X,Y ^ q(X,Y),List).

Exercise 11.3

Write a predicate `sigma/2` that takes an integer and calculates the sum of all intergers from 1 to . E.g.

`?- sigma(3,X).X = 6yes?- sigma(5,X).X = 15yes`

Write the predicate such that results are stored in the database (of course there should always be no more than one result entry in the database for each value) and reused whenever possible. So, for example:

`?- sigma(2,X).X = 3yes?- listing.sigmares(2,3).`

When we then ask the query

`?- sigma(3,X).`

Prolog will not calculate everything new, but will get the result for `sigma(2,3)` from the database and only add 3 to that. Prolog will answer:

`X = 6yes?- listing.sigmares(2,3).sigmares(3,6).`

Patrick Blackburn, Johan Bos and Kristina Striegnitz
Version 1.2.5 (20030212)