How to Build an Expert System with Prolog | AI Tutorial

How to build an Expert system with Prolog

1 Introduction

An expert system is a rule based program that tries to act like a human expert in a narrow domain. With Prolog you can express rules and facts in a natural logic style, so Prolog fits expert systems well.

Darija: النظام الخبير هو واحد النوع ديال البرامج اللي كيتصرف بحال خبير حقيقي فمجال محدد وصغير. مع Prolog نقدرو نكتبو القواعد والحقائق بطريقة منطقية وبسيطة، وهاد الشي كيجعل Prolog مناسب بزاف للنظم الخبيرة.

In this tutorial you learn how to build a simple expert system with Prolog. You see core ideas, then code examples, then practice exercises.

2 Core Concepts Explained

2.1 What is an expert system

An expert system tries to answer questions or give advice in a domain like medicine, troubleshooting, or recommendation. Main parts:

  • Knowledge base contains facts and rules about the domain
  • Inference engine uses logic to answer questions from the user
  • User interface asks questions and prints results

Darija: النظام الخبير كيحاول يجاوب على الأسئلة ولا يعطي نصائح فمجال معين بحال الطب، إصلاح الأجهزة، ولا الاقتراحات. عندو ثلاثة ديال المكونات الرئيسية

  • قاعدة المعارف فيها الحقائق والقواعد على المجال
  • محرك الاستدلال كييستعمل المنطق باش يخرج أجوبة من القواعد
  • واجهة المستخدم كتطرح الأسئلة على المستخدم وكتوريه النتائج

2.2 Why Prolog for expert systems

  • Prolog is logic based
  • You write facts and rules in a direct way
  • The inference engine of Prolog uses backward chaining
  • You focus on knowledge, not on low level control flow

Darija: Prolog مبني على المنطق، وكيخليك تركز على المعارف والقواعد بلا ما تغرق فالتفاصيل ديال التحكم فالكود. محرك Prolog كيدير الاستنتاج بالرجوع للوراء، يعني كيبدا من الهدف وكيقلب على القواعد اللي توصّلو ليه.

2.3 Key Prolog concepts for expert systems

  • Fact simple statement about the world
  • Rule conclusion that depends on conditions
  • Query question that you ask to the system
  • Variables start with uppercase and stand for unknown values

Darija: الحقائق هي جُمل بسيطة كتوصف العالم القواعد هي استنتاجات مرتبطة بشروط والاستعلام هو السؤال اللي كنسولو للنظام المتغيّرات فـ Prolog كيبداو بحرف كبير وكيعبرو على قيم مجهولة.

3 Prolog Syntax and Structure for Expert Systems

3.1 Facts

Example facts for diseases and symptoms

% disease(Name)
disease(flu).
disease(cold).

% symptom(Disease, Symptom)
symptom(flu, fever).
symptom(flu, cough).
symptom(cold, cough).
symptom(cold, sneezing).

English: Each line is one fact. Darija: كل سطر هنا واحد الحقيقة بسيطة.

3.2 Rules

Rules describe when something holds. Example rule for a disease if a person has some symptoms.

% has_disease(Person, Disease)
has_disease(Person, flu) :-
    has_symptom(Person, fever),
    has_symptom(Person, cough).

has_disease(Person, cold) :-
    has_symptom(Person, cough),
    has_symptom(Person, sneezing).

Here :- reads as "if". On the right side you see conditions separated by commas. Prolog treats comma as logical AND.

Darija: الرمز :- كنقراوه "إلا". الشرطين مفصولين بـ , وهاد الشي كيعبّر على "و" منطقية.

3.3 Queries

You ask the system using queries in the Prolog console.

?- has_disease(ali, flu).
?- has_disease(Who, flu).

First query checks if Ali has flu. Second query asks for all people with flu.

Darija: فأول استعلام كنشوفو واش علي عندو la grippe فالثاني كنطلبو جميع الناس اللي عندهم la grippe.

4 Example 1 – Simple Medical Expert System in Prolog

4.1 Knowledge base

% facts about symptoms of diseases
disease(flu).
disease(cold).

symptom(flu, fever).
symptom(flu, cough).
symptom(flu, body_ache).

symptom(cold, cough).
symptom(cold, sneezing).
symptom(cold, runny_nose).

% user symptom facts
has_symptom(ali, fever).
has_symptom(ali, cough).
has_symptom(sara, cough).
has_symptom(sara, sneezing).

4.2 Reasoning rules

% a person has a disease if person has all symptoms linked to that disease
possible_disease(Person, Disease) :-
    disease(Disease),
    symptom(Disease, Symptom),
    has_symptom(Person, Symptom).

This rule says Person has a possible disease if disease exists, symptom belongs to disease, and person has same symptom. You can ask

?- possible_disease(ali, D).
?- possible_disease(sara, D).

Darija: القاعِدة كتعني إلا كان مرض معيّن وعندو واحد العَرَض وهاد العَرَض موجود عند الشخص النظام كيعتبر هاد المرض احتمال عند هاد الشخص ومن بعد نقدر نسول Prolog على الأمراض المحتملة عند علي ولا سارة.

4.3 Simple interactive question system

Now build a small expert system that asks the user about symptoms.

% ask user about a symptom
ask(Symptom) :-
    write('Do you have '),
    write(Symptom),
    write('? (yes or no) '),
    read(Reply),
    Reply == yes.

% dynamic facts to store user answers
:- dynamic has_symptom_user/1.

% gather symptoms from user
collect_symptoms :-
    symptom(_, Symptom),
    \+ has_symptom_user(Symptom),
    ask(Symptom),
    assertz(has_symptom_user(Symptom)),
    fail.
collect_symptoms.

% reason using user symptoms
user_possible_disease(Disease) :-
    disease(Disease),
    symptom(Disease, Symptom),
    has_symptom_user(Symptom).

run_expert_system :-
    retractall(has_symptom_user(_)),
    collect_symptoms,
    write('Possible diseases '), nl,
    user_possible_disease(D),
    write(D), nl,
    fail.
run_expert_system.

Now in the Prolog console run

?- run_expert_system.

System asks questions then prints possible diseases.

Darija: منين تشغّل run_expert_system النظام كيسوّل المستخدم على الأعراض ومن بعد كيعطيه لائحة ديال الأمراض المحتملة.

5 Example 2 – Animal Classification Expert System

5.1 Facts and rules

% animal facts
animal(dog).
animal(cat).
animal(bird).

has_feature(dog, mammal).
has_feature(dog, four_legs).
has_feature(dog, barks).

has_feature(cat, mammal).
has_feature(cat, four_legs).
has_feature(cat, meows).

has_feature(bird, two_legs).
has_feature(bird, flies).

% rule for classification
classify(Animal, mammal) :-
    has_feature(Animal, mammal).

classify(Animal, quadruped) :-
    has_feature(Animal, four_legs).

classify(Animal, flying_animal) :-
    has_feature(Animal, flies).

You can ask

?- classify(dog, Class).
?- classify(bird, Class).

Darija: هنا عندنا نظام خبير بسيط كيصنّف الحيوانات حسب المميزات ديالهم بحال واش هو mammal ولا كيطرّ فسماء.

6 Example 3 – Simple Course Recommendation Expert System

6.1 Knowledge base

% user preferences
interest(user1, ai).
interest(user1, programming).

course('Intro to AI', ai, beginner).
course('Machine Learning with Python', ai, intermediate).
course('Prolog for AI', ai, intermediate).
course('Python Basics', programming, beginner).
course('Data Structures', programming, intermediate).

% rule to recommend
recommend(Person, Course) :-
    interest(Person, Topic),
    course(Course, Topic, Level),
    Level == beginner.

recommend(Person, Course) :-
    interest(Person, Topic),
    course(Course, Topic, Level),
    Level == intermediate.

Query examples

?- recommend(user1, Course).

Darija: فهاد المثال النظام كيقترح دورات حسب الاهتمامات ديال المستخدم بحال ai ولا programming.

7 Explanation of Key Parts

7.1 Backward chaining in Prolog

Prolog tries to prove a goal by looking for rules where goal appears in the head. Then it tries to satisfy conditions in body step by step. You do not write the inference engine yourself. Prolog handles search and unification.

Darija: منين كتعطي هدف لـ Prolog هو كيقلب على القواعد اللي الرأس ديالها هو نفس الهدف من بعد كيبدا يحقّق الشروط واحد بواحد إنت غير كتركز على الحقائق والقواعد و Prolog كيدير الخدمة ديال الاستنتاج.

7.2 Knowledge base design

You design a good expert system when you:

  • Pick a narrow domain like small medical subproblem or toy diagnostic task
  • List important concepts as predicates
  • Write clear facts with simple arguments
  • Write rules with small bodies and clear logic

Darija: باش تصايب نظام خبير مزيان اختار مجال صغير وواضح حدّد المفاهيم المهمة فشكل predicates ومن بعد كتب الحقائق والقواعد بطريقة بسيطة.

7.3 User interaction part

For real systems you:

  • Ask user questions
  • Store answers as dynamic facts
  • Run inference using those dynamic facts
  • Show results or explanations

Prolog gives assertz and retract for dynamic facts. You saw this in the medical example with has_symptom_user.

Darija: فالنظام الحقيقي كتسول المستخدم كتسجّل الأجوبة فحقائق ديناميكية ومن بعد كتحسب النتائج وكتوري المستخدم التفسير والنتيجة.

8 Step by Step – Build Your Own Expert System in Prolog

Step 1 Choose a domain

Examples:

  • Plant disease hints
  • Computer network troubleshooting
  • Car starting problems
  • Study path advice for AI

Darija: أول خطوة هي تختار مجال مثلا أمراض النباتات أو مشاكل الحاسوب أو اقتراحات الدراسة فمجال الذكاء الاصطناعي.

Step 2 Define predicates

Decide names for:

  • Facts about entities, for example problem/1, symptom/2, has_feature/2
  • Derived knowledge, for example diagnose/2, recommend/2, classify/2

Darija: اختار الأسماء ديال الـ predicates بحال symptom للأعراض ولا recommend للاقتراحات.

Step 3 Write facts

Enter fixed knowledge as facts.

problem(bad_battery).
problem(no_fuel).

symptom_problem(bad_battery, engine_clicks).
symptom_problem(no_fuel, engine_silent).

Step 4 Write rules

diagnose(Problem) :-
    symptom_problem(Problem, Symptom),
    has_symptom_user(Symptom).

Then later you add rules for recommendation or explanations.

Step 5 Add simple question interface

Reuse pattern from previous ask and collect_symptoms predicates. Adapt names for your domain, for example question_feature instead of symptom.

Step 6 Test and extend

Run many queries. Check if answers match expert expectations. Adjust rules and add more facts.

Darija: جرّب النظام مع بزاف ديال الأمثلة شوف واش النتائج قريبة من رأي خبير حقيقي إلا لقيتي خطأ بدّل القواعد وزيد حقائق جديدة.

9 Practice Exercises – Prolog Expert Systems

Use these exercises to strengthen your understanding of expert systems in Prolog. Try to write full Prolog files and test in a Prolog interpreter like SWI Prolog.

  1. Build an expert system for recommending a drink Inputs temperature (hot or cold), time of day, and caffeine preference Output drink like tea, coffee, juice Use facts for properties and rules for recommendation.
  2. Create an animal expert system Ask about features like has_fur, lays_eggs, lives_in_water Infer animal group like mammal, bird, fish.
  3. Extend the medical example Add new disease and symptoms Add rule for high risk case when user has certain combination of symptoms.
  4. Design a laptop selection expert system Facts about laptops and properties like ram_16gb, gpu_midrange Rules that recommend laptops for gaming or for study.
  5. Implement explanation feature When system suggests a disease or recommendation Add predicate explain/1 that prints reasons using rules.
  6. Add certainty levels Store facts symptom_weight(Disease, Symptom, Weight) Compute a score per disease based on user symptoms Print diseases sorted by score or at least print scores.
  7. Build a course advisor for AI learning Inputs background (math, programming) and goals (research, industry) Output learning path or next course suggestion.
  8. Make a simple troubleshooting expert system for Wi Fi Ask user questions about lights, distance, other devices Output advice step to try next.
  9. Add persistence Use file predicates like tell and told or modern equivalents Save user answers or logs to a file then read them back in a new session.
  10. Combine two expert systems First part diagnoses car battery issue Second part recommends next action such as call mechanic or charge battery Connect them with shared facts.
  11. Bonus in Darija صايب نظام خبير صغير كيعطي نصيحة على شنو تقرا فمجال الذكاء الاصطناعي دخّل مستوى المستخدم مبتدئ ولا متوسط واهتمام ديالو vision ولا NLP ولا reinforcement learning وخليه يقترح ليه واحد الكورس ولا كتاب.

Darija: حاول تحل هاد التمارين بوحدك كتب الكود فملف Prolog وجرّبو فـ SWI Prolog ولا أي مفسّر آخر كل مرة شوف النتيجة وعدّل القواعد حتى توصل لنظام خبير معقول.

10 SEO Keywords and Internal Linking Ideas

Include these phrases in titles or text when you write about this topic:

  • Prolog expert system tutorial
  • How to build an expert system with Prolog
  • AI expert system in Prolog
  • Rule based system in artificial intelligence
  • Knowledge base and inference engine in Prolog

Suggested internal links for a learning site:

[internal link: Machine Learning Basics]

[internal link: Neural Networks Guide]

[internal link: Intro to Prolog for AI]

[internal link: Rule Based Systems in AI]

[internal link: Knowledge Representation in AI]

Darija: من بعد هاد الدرس تقدّر تنتاقل لدروس أخرى بحال Machine Learning Neural Networks ولا Intro to Prolog for AI باش تكمل رحلة التعلم فمجال الذكاء الاصطناعي.

Share:

Ai With Darija

Discover expert tutorials, guides, and projects in machine learning, deep learning, AI, and large language models . start learning to boot your carrer growth in IT تعرّف على دروس وتوتوريالات ، ومشاريع فـ الماشين ليرنين، الديب ليرنين، الذكاء الاصطناعي، والنماذج اللغوية الكبيرة. بّدا التعلّم باش تزيد تقدم فـ المسار ديالك فـ مجال المعلومات.