# Prolog

## Getting started with Prolog and logic programming

Prolog is a general purpose logic programming language. If you have never heard of this language and are a SQL aficionados, you will recognize the way of writing code in this language, which feel quite like a query. This is a declarative language or a rule based language like SQL. Note that in “normal” languages that you encounter, like C, Java, Python, you generally write out the ways in which you retrieve the data or do the computation. Here, you will just be defining what you want instead of writing out explicitly how to get it. Feels wonderful, isn’t it? Now, since this is a vast language by itself, only a minuscule part will be looked at.

• install swipl
• take a look at some basic examples to have some idea on how prolog code looks like
• ruminate on some basic ways in which we can reason about code

### SWIPL

SWI-Prolog is one of the most comprehensive implementation for prolog. It is also very widely used. You can use the SWI-Prolog interpreter to run the programs. To install the interpreter in ubuntu you can run the following commands.

`sudo add-apt-repository ppa:swi-prolog/stable`
`sudo apt-get update`
`sudo apt-get install swi-prolog`

Now, create a new hello.pl and type the below lines:

You have created a hello world program for prolog. In the terminal, run the following command to run this file and you should get the output in the terminal.

`➜  swipl -q -f hello.pl -t mainHello World`

### Some code examples

Take a look at some code samples to understand the flow of logic in a prolog code. To show relationships between data, write in the following format.

`verb(noun1, noun2)`

which means that there is a relationship from `noun1` to `noun2` via relationship `verb` . Using this define the following relationships.

This is logic programming where the facts and rules of the problem domain is defined. The following code will list the members of fruit class.

This is called a query. Save this to a `listing.pl` file and then execute the query. The command is written as:

swipl -q -f <filename> -t <query function name or goal>

`➜  swipl -q -f listing.pl -t main fruit(apples).fruit(plums).`

This shows a listing of all the relationships in the data.

Similarly, based on the existing relationships, write the names of the people who have apples or plums.

Run the file in the terminal using the interpreter

`➜  prolog swipl -q -f listing1.pl -t mainjackann`

You can find the whole file in this github gist.

Now as an exercise can you find the people who have both apples and plums. Share the gist in the comments below.

In case you found this interesting and would like to talk more on this, just drop me a message @alt227Joydeep. I would be glad to discuss this further. You can also hit the like button and follow me here, on Medium.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.