Prolog For Python Programmers

Differences in the Interpreter

One gotcha is that the Prolog interpreter runs in a query mode, while code in file runs as assertions. Python, on the other hand, makes no such distinction. Code that you can compile in a file can equally be typed into the interpreter.

i.e. You have to write the rules in a text file, and then load it in the interpreter before querying.


% In a file-------------
% test.pl
% A Person has age, height and weight
person(john,  25, 165, 75).
person(mary, 13, 125, 30).
person(gary,  66, 180, 90).
person(gale,  65, 169, 70).
person(mark, 26, 182, 95).

% ------- Run in the interpreter -----------
% Loads file. equivalent to consult('test.pl').
['test.pl'].

Variables

A rather crude way of doing variables in Prolog is via assertions and retraction.


assert(num_flowers(25)).
num_flowers(NumFlowers).
NumFlowers = 25

List comprehensions, filter


% older = [person for person in persons if age > 20]
findall(
  person(Name, Age, Height, Weight),
  (person(Name, Age, Height, Weight), Age > 20),
  Older).

Older = [person(john, 25, 165, 75),
 person(gary, 66, 180, 90),
 person(gale, 65, 169, 70),
 person(mark, 26, 182, 95)]

Access to members of a tuple (Term) and map

% total_height_older = [person[2] for person in older]

maplist(arg(2), $Older, Heights), sumlist(Heights, TotalHeight).
Heights = [25, 66, 65, 26],
TotalHeight = 182

Mind Reading

Incidentally, SWI-Prolog is astonishingly clever at reading minds. Here’s an interactive session where I misspelt person with erson.

7 ?- erson(john, Age, Height, Weight).
Correct to: person(john, Age, Height, Weight)? yes

Age = 25,
Height = 165,
Weight = 75

Reference

[1] comp.lang.prolog

One Response to “Prolog For Python Programmers”

  1. mat writes:

    To enter programs on the toplevel, type:

    ?- [user].

    then type your program and finish with RET and Ctrl+d.

Leave a Reply