Permalink
Browse files

exercises of section 2.5

  • Loading branch information...
fxn committed Jul 16, 2011
1 parent 5757114 commit 28ebde2a9ba7dc2a791aaa183016a4e759567846
Showing with 62 additions and 0 deletions.
  1. +48 −0 chapter02/exercise-2.5.1.pl
  2. +14 −0 chapter02/exercise-2.5.2.pl
@@ -0,0 +1,48 @@
+/* Get print_capitals working on your computer. Try the query
+
+ ?- print_capitals, write('All done.').
+
+with and without Clause 2. What difference does Clause 2 make? */
+
+:- consult(capitals).
+
+print_a_capital :-
+ capital_of(State, City),
+ write(City),
+ write(' is the capital of '),
+ write(State),
+ nl.
+
+print_capitals :-
+ print_a_capital,
+ fail.
+
+print_capitals. % Clause 2
+
+/*
+
+With Clause 2 the result is
+
+ ?- print_capitals, write('All done.').
+ atlanta is the capital of georgia
+ sacramento is the capital of california
+ tallahassee is the capital of florida
+ augusta is the capital of maine
+ All done.
+ true.
+
+Without Clause 2 is
+
+ ?- print_capitals, write('All done.').
+ atlanta is the capital of georgia
+ sacramento is the capital of california
+ tallahassee is the capital of florida
+ augusta is the capital of maine
+ false.
+
+The difference is that "All done." is not printed, and we get a final failure.
+This happens because without Clause 2 print_capitals necessarily fails once
+all the backtracking has taken place, and thus the second goal, write, is
+not even tried.
+
+*/
@@ -0,0 +1,14 @@
+/* Go back to FAMILY.PL and your solution to exercise 2.4.4. Define a predicate called
+print_ancestors_of that takes one argument (a person's name) and prints out the
+names of all the known ancestors of that person, in the same format as in Exercise 2.4.4. */
+
+:- consult('exercise-2.4.4').
+
+print_ancestors_of(Person) :-
+ write('The ancestors of Cathy are: '),
+ ancestor(X, Person),
+ write(X),
+ write(' '),
+ fail.
+
+print_ancestors_of(_).

0 comments on commit 28ebde2

Please sign in to comment.