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 read() and write().

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:

?- 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 read().

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 every time that I am stuck 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 descendants!

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

?- 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