PROLOG - Part 5


Against logic there is no armor like ignorance.


I/O in PROLOG

Until the last post, we saw how to build rules and query facts. But all we can see as “answer” until now are some ‘yes’ or ‘false’. Pretty boring hum… But as in other languages, PROLOG also offers I/O support: please meet the methods

and ```write()```.
1
2
3
4
5
6
7
8
9
10
11
12

## Finally our PROLOG "Hello world!"

Try it out. Yes, just like that! Save the line of code ```hello :- read(X), write("Hello "), write(X). ``` in a file named ```hello.pl``` . Then start your swipl and type:

```bash
?- consult("hello.pl").
true.

?- hello. "World!".
Hello World!
true.

You need to agree with me now that PROLOG is waaayyy easier than in the most of the other languages that you learned before, right? ;) It’s important to notice that we call the rule “hello” without any arguments and just after that we can pass the input to the

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

> Note that after each PROLOG instruction you need a dot!

What we know as "Strings" from other languages should be written in PROLOG always inside " ". Input written outside " " will be interpreted and you would have a strange output...

## Recursion

If you tried to implement ```ancestor``` as I suggested in the last post, you probably got it already. But if not, I figured that _RECURSION_ is still a big deal and deserves at least a small discussion here.

Thinking recursively is something that needs practice. I have a "technique" that helps me everytime that I am stucked with some problem that I want to solve recursively.

* First I solve the problem for the baseline (as in Math, you can think you are computing the ```x = 0``` or ```x = 1``` cases). In our family example, you could write the _base rule_ as:

`ancestral(X,Z):-parent(X,Z).`

* After that, you define the _recursive rule_ (or the `x = n + 1` cases):

```ancestral(X,Z):-parent(X,Y), ancestral(Y,Z).

With this we can now ask who are Sarah’s decendents!

For that, add these two lines of code in your family.pl file, start your swipl and type:

1
2
3
4
5
6
7
8
9
10
11
?- consult("family.pl").
true.

?- ancestral(sarah,X).
X = isaac ;
X = esau ;
X = jacob ;
X = joseph ;
false.

?-

and with “;” you can query all the possible answers for your question, as we learned before!

Next post: Backtracking