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.

Gallaire

Prolog as a Database Query Language

Warren

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

Deductive Databases

A Brief Introduction to Deductive Databases

Ullman

https://www3.cs.stonybrook.edu/~warren/xsbbook/node12.html

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

https://www3.cs.stonybrook.edu/~warren/xsbbook/node5.html

Pseudocode (rewrite in JavaScript)

  sum(List,Sum) :-
    if List = []
      then Sum := 0
    else Head := head(List)
      Tail := tail(List)
      sum(Tail,TailSum)
      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.

Nondeterminism

https://www3.cs.stonybrook.edu/~warren/xsbbook/node6.html

ODBC

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

[postgresql]
Description         = Test to Postgres
Driver              = /usr/lib/psqlodbcw.so
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

CQL

cql

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