MASINDE MULIRO UNIVERSITY OF SCIENCE AND TECHNOLOGY
SCHOOL OF COMPUTING AND INFORMATICS
DEPARTMENT OF COMPUTER SCIENCE
CSC 227: LOGIC PROGRAMMING
OPEN BOOK CAT [X/60 MARKS] MARCH 2025
INSTRUCTIONS:
Answer all questions comprehensively.
Provide well-structured responses with justifications.
Use real-world applications, programming examples of Prolog predicates, and case
studies where applicable.
Use all sorts of reference materials in the examination room apart from Mobile phones
and Generative AI.[Any generated answers will Not be marked and you will deemed to
have failed the CAT and NO make-up CAT for you.]
1. Logic programming differs from procedural and object-oriented programming in its approach
to problem-solving, relying on declarative statements rather than sequential execution. Explain
how logic programming contrasts with these paradigms, particularly in how it defines relationships
and rules instead of explicit control flow. Consider a traffic control system that dynamically adjusts
signals based on real-time traffic conditions. Discuss why a Prolog-based system would be more
effective in handling such conditions compared to an imperative programming approach. Provide
specific advantages such as rule-based inference, pattern matching, and non-deterministic
execution in logic programming. [4 marks]
2. Traditional logic programming assumes that facts and rules are static and absolute, but in many
real-world scenarios, information can change or be incomplete. Explain how uncertainty is
managed in logic programming, particularly through non-monotonic reasoning where conclusions
may need to be retracted when new information is introduced. Provide a scenario where default
reasoning or defeasible logic would be required, such as in an AI-powered recommendation system
where user preferences evolve over time. Discuss how Prolog can be adapted to support such
reasoning. [4 marks]
3. Consider the following Prolog program for an ancestor relationship:
parent(john, mary).
parent(mary, susan).
parent(mike, tom).
parent(tom, jane).
ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).
1
A user queries ?- ancestor(john, jane). and notices that the program enters an infinite loop in some
cases. Analyze the logic behind this issue, explain why infinite recursion may occur, and suggest
a modification to the recursive rule to prevent it while maintaining correctness. [4 marks]
4. Given the Prolog query:
loves(john, X) = loves(Y, mary).
Explain the unification process that Prolog performs in this query. What are the possible values
for X and Y based on Prolog’s term-matching mechanism? Modify the query to ensure that
backtracking is eliminated, allowing Prolog to return only one correct answer. [4 marks]
5. A fraud detection system needs to flag suspicious banking transactions based on the following
conditions:
If a transaction exceeds KES 10,000, it should be flagged immediately.
If a transaction happens within 5 minutes of another flagged transaction, it should also be
flagged.
Write a Prolog rule using the cut predicate (!) to optimize fraud detection, ensuring that once a
transaction is flagged, no further backtracking occurs. Explain why the cut predicate is necessary
in this scenario to prevent redundant checks. [5 marks]
6. A university wants to classify students into four categories based on their average performance
and recent trends:
Exceptional (≥ 90%)
Good (75<90%)
Average (50<75%)
At Risk (<50%)
Write a Prolog predicate that classifies students based on their scores while also considering
performance trends (improving or declining). Use list processing to calculate averages and
incorporate a cut predicate (!) to ensure efficient classification. [5 marks]
Example Query:
?- classify_student(jane, [85, 90, 92], Category).
Category = exceptional.
7. Develop a Prolog-based medical expert system that diagnoses diseases based on symptoms
and prior medical history. The system should:
Diagnose Flu if the patient has fever, cough, and sore throat.
Diagnose Malaria if the patient has fever, chills, and sweating.
Diagnose COVID-19 if the patient has fever, cough, and difficulty breathing.
2
If a patient has persistent fever and body pains, but recently recovered from another
illness, the system should ask whether it is a relapse case before making a final diagnosis.
Write facts and rules for the system in Prolog, ensuring that it handles conflicting symptoms and
past medical records intelligently. [7 marks]
Example Query:
?- diagnose(john, [fever, cough]).
Diagnosis = COVID-19.
8. A Prolog-based Intrusion Detection System (IDS) is required to classify network activities as
safe or malicious based on predefined security rules. The system should:
Detect suspicious activity if an IP makes repeated failed login attempts within 10 minutes.
Flag activity as high risk if an unauthorized file access attempt occurs.
Automatically block high-risk IP addresses.
Write a Prolog program that implements these security rules and ensures efficient execution
using cut predicates (!) to prevent unnecessary evaluations.
Example Query:
?- detect_intrusion(ip_192_168_1_5).
Response = "Blocked - Multiple unauthorized access attempts".
[7 marks]
9. Consider the following knowledge base about store transactions:
item(sugar, 150).
item(bread, 110).
item(milk, 65).
item(drinking_chocolate, 180).
item(salt, 45).
item(coffee, 250).
transaction(monday, john, [sugar, bread, milk]).
transaction(tuesday, mary, [coffee, sugar, salt]).
transaction(wednesday, john, [milk, bread]).
transaction(thursday, susan, [drinking_chocolate, coffee]).
transaction(friday, mary, [sugar, bread, coffee]).
discount(Total, Rate) :- Total >= 1000, Rate is 0.1.
discount(Total, Rate) :- Total >= 500, Total < 1000, Rate is 0.05.
discount(Total, Rate) :- Total < 500, Rate is 0.
bill_amount(Day, Customer, Amount) :-
transaction(Day, Customer, Items),
calculate_total(Items, SubTotal),
discount(SubTotal, Rate),
Amount is SubTotal * (1 - Rate).
3
calculate_total([], 0).
calculate_total([Item|Rest], Total) :-
item(Item, Price),
calculate_total(Rest, RestTotal),
Total is Price + RestTotal.
a) Identify and explain each of the following Prolog components in the knowledge base above:
Atoms (provide at least 5 examples)
Predicates (provide all examples with their arity)
Facts (provide at least 3 examples)
Rules (provide all examples)
Variables (provide all examples)
b) Trace through the resolution process step by step when the following query is executed:
?- bill_amount(friday, mary, X).
Show each step of unification, backtracking (if any), and variable binding that occurs during the
resolution process. Explain how Prolog's matching algorithm and depth-first search strategy is
applied to resolve this query.
c) Modify the knowledge base to add a rule called frequent_buyer/1 that identifies customers
who have made more than one transaction. Explain how you would use the built-in aggregation
predicates like findall/3 and length/2 to implement this rule.
[10 marks]
10. Design a Prolog program that manages a shopping bill system for a store. Your program should:
1. Maintain a database of items with their prices (sugar at 150 KES, bread at 110 KES, milk
at 65 KES, drinking chocolate at 180 KES, etc.)
2. Allow a user to create a shopping list with quantities
3. Generate an itemized bill showing individual costs and the total
4. Implement the following features using appropriate built-in predicates:
o Sort the final bill by price (highest to lowest)
o Filter items above a certain price threshold
o Calculate the average price of items purchased
o Find the most expensive and least expensive items
o Apply different discount rates based on total bill amount
Explain how you used built-in predicates like findall/3, sort/2, keysort/2, include/3,
exclude/3, sum_list/2, length/2, and maplist/3 in your solution. Demonstrate how you
would query your program to generate a sample bill for a customer who purchases 2kg of sugar, 3
loaves of bread, 1 carton of milk, and 500g of drinking chocolate [10 marks]