Tutorial: Learn Prolog Language by Creating an Expert System

Prolog is a logic programming language associated with artificial intelligence and computational linguistics.

Chaudhry Talha šŸ‡µšŸ‡ø
Analytics Vidhya

--

In this topic, weā€™ll learn PROLOG from basics and then build a small expert system that will suggest songs to a person based on their personality and mood. The best way to learn a new language is to create an idea in it and this is exactly what our focus is going to be.

What is Prolog?

Prolog is a declarative programming language that is a short form of PROgramming LOGic. Itā€™s a fourth-generation programming language.

A declarative language is a language in which a programmer specifies a goal to be achieved and prolog system works out how to achieve it.

Here is the Wikipedia for Prolog you can learn more about https://en.wikipedia.org/wiki/Prolog

Downloading and Installation of Prolog:

Go tohttps://www.swi-prolog.org/download/stable and download the one which is suitable for the operating system. SWI Prolog is an IDE on which it is super easy to write and run prolog code. After a successful installation when you run it by clicking on the red owl icon itā€™ll open this:

Prolog Console

This is the prolog console that will be used to execute and run our prolog code.

Prolog Syntax:

Before we start writing prolog code you need to understand that prolog is an old language. If you are coming from a modern-day programming background, it might be a pain in the brain. But itā€™s actually very simple as there are just a few things to remember, and you can create great expert systems but of-course like other languages it can get complex but we are not going to go into that depth but itā€™ll give you the right confidence to explore more.

There are just five symbols or things that you have to remember which covers a lot of Prolog Syntax:

  1. :- means this arrow ā†’ (meaning ā€œit implies thatā€)
  2. , which means AND
  3. ; represents OR
  4. A any word written with a capital letter is a variable
  5. . represents end
  6. () for enclosing data/information

The use of these will be clear to you in the next section where weā€™ll do some examples before starting to build our music suggestions expert system.

Facts & Rules

This is the most important thing to understand as youā€™ll be writing facts and rules in prolog syntax and then prolog will come to a decision based on these facts and rules.

A FACT is basically a thing that is known or proved to be true. For example, Alex is a Male, Tweety is a Bird, A Bicycle has two tires.

Based on the facts we make RULES.

Example 1:
Facts: The bathroom is dry. The hall is wet. There is a leak in the kitchen.
Rule: IF the bathroom is dry AND the hall is wet THEN there is a leak in the kitchen.

Example 2:

If Alex is the father of Matt, and Matt is the father of Quinn that means Alex is the grandfather of Quinn.

The above example is not the right way to represent a rule, as we always make rules that are generic, but in this case, itā€™ll say that, if a person is Quinn his dad will be Matt which is not true because not all Quinnā€™s have a father named Matt.

So that is why we use variables to define generic rules. So in order to write a general rule for the above example, weā€™ll say:

If X is the father of Y, and Y is the father of Z that implies X is the grandfather of Z.

Now if we replace this rule and say X = Alex, Y = Matt, Z = Quinn, youā€™ll get the same statement we wrote at the start of this example.
So, you see the difference, now we have a rule that is a universal rule and we can apply it to every situation of father and grandfather relationship.

There is a concept called Predicate Logic which is used to write any rule on paper, which we are not going to get into so many details but this is how it is done when an AI engineer is making an expert system the write predicate logic to define facts and rules. In this article as we are focused on Prolog but because prolog works with predicates, you should at least know the symbols like āˆ€, āˆ§ and āˆØ.
Click here to learn more about predicate symbols OR This PDF about predicate symbols

Letā€™s see if we were to write the same rule in prolog, how would that look like.

The files which contain Prolog code have an extension .pl so this means that you can use any text editor like Notepad, TextEdit, Sublime, Atom etc just make sure that you save the file with .pl extension.

Open sublime or any text editor and write this:

father(alex,matt).father(matt,quinn).

In the above lines, we have written some facts. Itā€™s a fact that Alex is the father of Matt and Matt is the father of Quinn.

Now letā€™s write our rule. After the last line add:

grandfather(X,Y):-father(X,Z),father(Z,Y).
Save this file and give it a name and extension as grandfather.pl

The above line reads:

X is the grandfather of Y, this implies that X is the father of Z and Z is the father of Y.

So, now you see how the symbols we discussed in the previous section come into action? The names grandfather and father are defined by us, which weā€™ll use to ask questions to our system like who is the grandfather of Quinn etc youā€™ll see in a minute.

Open SWI-Prolog, and from the menu select File > Consult and select the grandfather.pl file in the file browser. Itā€™ll show a green message which indicates that it was imported correctly.

Now we can ask a number of questions to the system, like:

  1. Who is the father of matt? father(K,matt).
  2. Who is the grandfather of Quinn? grandfather(V,quinn).
  3. Is Alex is the grandfather of Quinn? grandfather(alex,quinn).

Here K and V are variables that we are trying to find out. They can be anything and this is what Prolog is doing, using the knowledge we have provided and coming to a solution.

In a real-world scenario, the facts are usually collected from the user. For example, if Iā€™ve written down grandfather(david,bella) the system would ask me that who is the father of bella? Letā€™s say I write bernie and then the system asks me that is david the father of bernie and if I reply yes then the system will return true. For the sake of this example, Iā€™ve hardcoded the facts but after finishing this article you can easily scale this example to that level.

So, at this point, youā€™ve actually made a tiny expert system. You can expand it by adding more to the knowledge base i.e. providing facts like who is the father of Alex and so on. But, letā€™s create an expert system that includes a step-by-step process of building an actual expert system, in the next section.

Letā€™s Build an Expert System:

Remember prolog is an old language and it is highly likely that anyone uses it nowadays. You can see What is Prolog used for today? and know for yourself. Because what we are about to do is a small expert system that suggests a song to you based on your personality type and mood.

Right now you have written some Prolog code and you know the concepts like facts and rules. In order to make the rules efficient and easily there is a concept called Factor Table.

A factor table is a simple table that can be made using an excel sheet and is a part of Knowledge Representation.
Knowledge representation is a brief note of the expert system.
In the factor table, we just represent the knowledge we have and this makes it easy for us to write rules and facts.

So here are the steps of how our expert system will be created:

  1. Write a brief description of the knowledge we have for the system and from that knowledge, weā€™ll make the factor table
  2. From the factor table, weā€™ll write rules (production rules)
  3. Write those rules in the prolog

Note that all of these steps are useful to write a successful prolog program. Otherwise, it might get confusing because managing knowledge is super stressful and requires a lot of attention. So letā€™s start!

Brief Note & Factor Table

Using the knowledge from https://www.16personalities.com/articles/music-preferences-by-personality-type and https://infj-mbti.tumblr.com/post/106640511443/myers-briggs-music-tastes we know that there are 16 types of general personalities:

  • ENTJ, INTJ, ENTP, INTP
  • INFJ, INFP, ENFJ, ENFP
  • ISTJ, ISFJ, ESTJ, ESFJ
  • ISTP, ISFP, ESTP, ESFP

For the purpose of this tutorial, Iā€™m only considering 2 types of moods. We are categorizing moods generally in these two types:

  • Happy
  • Sad

So, we just need to ask the person these questions:

  1. Are you an Introvert or Extrovert?
    Are you Intuitive or Observant?
    Are you Thinking or Feeling?
    Are you Judging or Prospecting?
    (To simplify Iā€™ll just ask the user to enter their personality type)
  2. How is your mood?

So the top two questions will suggest a song link to the user. Letā€™s create a factor table which will simplify the knowledge for us.

Factor Table:

This is a factor table that Iā€™ve made using the brief note above:

Factor Table from Knowledge that we have

You can see how easy it becomes to see information when we add the English-like sentences of information into the factor table. The above factor table indicates:

If the personality type if ENTJ person is more likely to listen to Jazz, Classical and Electronica genre of music.
Ignore the % next to the genre we are not using it anywhere.

We can write the facts and rules using this but first, letā€™s make another factor table because we can make a simplified version of the above table. And this table will work as the main table based on which weā€™ll be writing our logic.

Itā€™s all about creating the factor table that makes it easier for you to understand and write code. This second/main factor table indicates that:

Personalities entj and enfj and enfp when happy listen to jazz so here is a link that we can suggest.

So, we are going to use the second one as our main table.

Production Rules & Predicate Logic

Letā€™s define some facts and rules along with that Iā€™ll write the predicate logic (itā€™s okay if you donā€™t understand predicate logic yet). So some facts would be:

So these are the basic facts that weā€™ll use for all of our logic. For example, if I have to write:

Suggest song link https://www.youtube.com/watch?v=c8YIlU_30Kk of jazz genre implies that the personā€™s mood is happy and he is of entj or enfj or enfp personality type.

In predicate logic, itā€™ll be:

āˆ€x: S(x,y) ā†’ M(x) āˆ§ P(x) āˆØ P(x) āˆØ P(x)

That is the only rule that weā€™ll need as itā€™s a small system.

Letā€™s code Prolog!

Remember the Prolog Syntax I discussed at the start of this article. Letā€™s use that to write a rule-based on our factor table.

song('https://www.youtube.com/watch?v=c8YIlU_30Kk',jazz,M,P):- M = happy ,(P= (entj) ; P=(enfj) ; P=(enfp)),!.

This line of code when translated to English becomes:

Song ā€˜https://www.youtube.com/watch?v=c8YIlU_30Kk' of jazz genre implies that mood is happy and personality is entj or enfj or enfp.

The above line of code indicates that for a song weā€™ll have song link and genre which are the known variables in this rule because we know it's a fact that this song is of which genre.
M which stands for Mood and P which stands for Personality are the unknown variables and will require the userā€™s input. Remember everything that is written with a capital letter at the start considered as a variable.

You can also see the usage of , and ; which represents AND and OR in prolog syntax. We used () to keep the OR conditions together.

! at the end of the line is called cut and is used to reduce backtracking. Itā€™s optional you can remove ,! if you want and itā€™ll not affect the output.

So Iā€™ve written a similar line as above for all the song links that I have in my factor table. Telling prolog which link belongs to which mood and personality.

song('https://www.youtube.com/watch?v=c8YIlU_30Kk',jazz,M,P):- M = happy ,(P= (entj) ; P=(enfj) ; P=(enfp)),!.
song('https://www.youtube.com/watch?v=SsZRci3sA4I',classical,M,P):- M = happy ,(P= (entj) ; P=(intj) ; P=(entp) ; P=(infj)),!.
song('https://www.youtube.com/watch?v=XYk2kt8K6E0',electronica,M,P):- M = happy ,(P= (entj) ; P=(estp) ; P=(enfp)),!.
song('https://www.youtube.com/watch?v=VguED7BfpgU',metal,M,P):- M = happy ,(P= (intj) ; P=(istp) ; P=(intp) ; P=(estp)),!.
song('https://www.youtube.com/watch?v=5f-wQBh-zbQ',alternative_rock,M,P):- M = happy ,(P= (intj) ; P=(entp) ; P=(infj) ; P=(infp) ; P=(istj) ; P=(isfj) ; P=(istp)),!.
song('https://www.youtube.com/watch?v=lPIiB02uqXM',rock,M,P):- M = happy ,(P= (entp) ; P=(intp) ; P=(infp) ; P=(istj) ; P=(isfj)),!.
song('https://www.youtube.com/watch?v=PIfJ7nYQFTM',punk,M,P):- M = happy ,(P= (intp) ; P=(infp) ; P=(istp)),!.
song('https://www.youtube.com/watch?v=eWyeAIlaYUY',world,M,P):- M = happy ,(P= (infj) ; P=(enfj)),!.
song('https://www.youtube.com/watch?v=qAqKsw4GjB0',blues,M,P):- M = happy ,(P= (enfj)),!.
song('https://www.youtube.com/watch?v=w47D1Fqn_sA',ambient,M,P):- M = happy ,(P= (enfp) ; P=(isfp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=HA06Rr3bRVc',pop_songs,M,P):- M = happy ,(P= (istj) ; P=(estj) ; P=(isfp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=qCZAynQU_-8',religious,M,P):- M = happy ,(P= (isfj) ; P=(estj)),!.
song('https://www.youtube.com/watch?v=hvVPMIqRulE',hip_hop,M,P):- M = happy ,(P= (estj) ; P=(estp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=X7ses5rI5U4',soul,M,P):- M = happy ,(P= (esfj)),!.
song('https://www.youtube.com/watch?v=NKzyyxvNiFc',country,M,P):- M = happy ,(P= (esfj)),!.
song('https://www.youtube.com/watch?v=oWQpQW95Ru8',reggae,M,P):- M = happy ,(P= (isfp)),!.
song('https://www.youtube.com/watch?v=McxPJ3RYY4Y',jazz,M,P):- M = sad ,(P= (entj) ; P=(enfj) ; P=(enfp)),!.
song('https://www.youtube.com/watch?v=R6OElQVVlLo',classical,M,P):- M = sad ,(P= (entj) ; P=(intj) ; P=(entp) ; P=(infj)),!.
song('https://www.youtube.com/watch?v=ilTbMVG5t6M',electronica,M,P):- M = sad ,(P= (entj) ; P=(estp) ; P=(enfp)),!.
song('https://www.youtube.com/watch?v=SWkKvDD-Gu4',metal,M,P):- M = sad ,(P= (intj) ; P=(istp) ; P=(intp) ; P=(estp)),!.
song('https://www.youtube.com/watch?v=-fvBrKeobyA',alternative_rock,M,P):- M = sad ,(P= (intj) ; P=(entp) ; P=(infj) ; P=(infp) ; P=(istj) ; P=(isfj) ; P=(istp)),!.
song('https://www.youtube.com/watch?v=qGxO2YNFj1o',rock,M,P):- M = sad ,(P= (entp) ; P=(intp) ; P=(infp) ; P=(istj) ; P=(isfj)),!.
song('https://www.youtube.com/watch?v=2MRdtXWcgIw',punk,M,P):- M = sad ,(P= (intp) ; P=(infp) ; P=(istp)),!.
song('https://www.youtube.com/watch?v=F90ymkS2dt4',world,M,P):- M = sad ,(P= (infj) ; P=(enfj)),!.
song('https://www.youtube.com/watch?v=6R9nWRWgl90',blues,M,P):- M = sad ,(P= (enfj)),!.
song('https://www.youtube.com/watch?v=sbX_aElB2dI',ambient,M,P):- M = sad ,(P= (enfp) ; P=(isfp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=T8-96tqFCFU&vl=en',pop_songs,M,P):- M = sad ,(P= (istj) ; P=(estj) ; P=(isfp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=K_-e99oLp4Y',religious,M,P):- M = sad ,(P= (isfj) ; P=(estj)),!.
song('https://www.youtube.com/watch?v=0pZmHnj3-jQ',hip_hop,M,P):- M = sad ,(P= (estj) ; P=(estp) ; P=(esfp)),!.
song('https://www.youtube.com/watch?v=KVIwQFEyZQE',soul,M,P):- M = sad ,(P= (esfj)),!.
song('https://www.youtube.com/watch?v=ygxmpkHgaC8',country,M,P):- M = sad ,(P= (esfj)),!.
song('https://www.youtube.com/watch?v=FqQjAUB6DJY',reggae,M,P):- M = sad ,(P= (isfp)),!.

The above messy code requires a lot of concentration to know if you have written down every rule correctly. Itā€™s the same song(_,_,_,_) that Iā€™ve defined above but for every personality type and for all moods and genres as per my factor table.
We use _ when we donā€™t want to give a variable value. _ is just used to fill the space but not to print anything.

So now we have the rules in place. The last thing is to ask users about their personality type and their mood so that we can fill the M and P variable.

There is a built-in predicate in prolog called read() and write() that weā€™ll use to take user input. So hereā€™s the code for that:

suggest(S) :- write('What is your personality type?: '),read(P),write('How is your mood?: '),read(M), song(S,_,M,P).

We have a simple predicate, named suggest(S) where S symbolizes as a song. Then we say write(what is your personality type?) and then wait to read(P) and then write(How is your mood?) and then again wait to read(M) and then call song(S,_,M,P)

As our song requires 4 variables and we only have three right now. So just to ignore genre, as itā€™s not important for the end-user to know, Iā€™m using _ as a replacement of genre.

Thatā€™s it! Letā€™s RUN IT!!!

Open SWI-Prolog and from the menu select File > Consult then in the console write:

suggest(Song).

and itā€™ll ask you the two questions and based on your answers itā€™ll print out the suggestion for you.

So you have successfully made your first artificial intelligent program. šŸ™Œ šŸŽ‰

Here is the full code:

Here is the link to the project on GitHub: https://github.com/thechaudharysab/LearningProlog

Conclusion:

This is the basic level of Artificial Intelligence. Think of AI as a child who is just born and knows nothing. Then the parents will teach them things like to walk, to speak, to eat, etc. Using this analogy we have just taught the computer with very limited knowledge like 1+1 will be equal to 2 and computer cannot think that 1+2 = 3 itself, you have to teach it. But there are concepts like Deep Learning, Fuzzy Logic, etc that encounter this to some level but they are more advanced topics.

https://www.buymeacoffee.com/chaudhrytalha
https://www.buymeacoffee.com/chaudhrytalha

As I always write ideas at the end, that you can do using the knowledge you have just acquired by reading this article so here are a few:

  1. Create a Robot version of yourself. Write everything that you know and give this knowledge to the computer and let your friends play along. [Expert level]
  2. Think of what is that one thing that you are an expert of? If you know about dogs create a program that suggests dog to a person based on the questions that you ask them. [Intermediate Level]
  3. Create a trip planning expert system. [Easy Level]
  4. Extend example 2 in this article. [Beginner level]

Feel free to comment if you can think of any more ideas Iā€™ll add them here.

--

--