Prolog basics

Good online resources

David S. Warren

Tabling and Datalog Programming

The notion of tabling, also sometimes called memoization or lemmatization, is very simple: never make the same procedure call twice: the first time a call is made, remember all the answers it returns, and if it's ever made again, use those previously computed answers to satisfy the later request.


Prolog as a Database Query Language


The term used for a database extended with logical rules is logic database or deductive database.

Deductive Databases

A Brief Introduction to Deductive Databases


Transitive Closure

tca(X,Y) :- a(X,Y).
tca(X,Y) :- a(X,Z), tca(Z,Y).

Modified to avoid cycles

tca(X, Visited, Y) :- a(X, Y), \+member(Y, Visited).
tca(X, Visited, Y) :- a(X, Z), \+member(Z, Visited), tca(Z, [Z|Visited], Y).

List recursion

Pseudocode (rewrite in JavaScript)

  sum(List,Sum) :-
    if List = []
      then Sum := 0
    else Head := head(List)
      Tail := tail(List)
      Sum := TailSum + Head

translated to Prolog with multiple procedures

  sum([], 0).
  sum([Head|Tail], Sum) :-
    sum(Tail, TailSum),
    Sum is TailSum + Head.

alternatively as a conventional, single procedure

sum2(List, Sum) :-
  List = [] ->
    Sum = 0
    List = [Head | Tail],
    sum2(Tail, TailSum),
    Sum is TailSum + Head.



Getting this to work requires having the PostgreSQL ODBC driver installed and a ~/.odbc.ini file that looks something like this:

Description         = Test to Postgres
Driver              = /usr/lib/
Trace               = Yes
TraceFile           = sql.log
Database            = games
Servername          = localhost
UserName            = my_username
Password            = my_password
Port                = 5432
Protocol            = 9.4
ReadOnly            = No
RowVersioning       = No
ShowSystemTables    = No
ShowOidColumn       = No
FakeOidIndex        = No
ConnSettings        =

SWI-Prolog ODBC Interface



  odbc_connect('postgresql', Connection, []),
  {}, % CQL query