Lurker News
Hi, i am a compsci student that stumbled upon prolog and logic programming during my studies.

While i have seen the basics of vanilla prolog (atoms, predicates, cuts, lists and all that jazz) and a godawful implementation of an agent communication system that works on SICStus prolog. I would like to know more because i think that this language might be a powerhouse in per se.
Since my studies are quite basic in this regards i would like to expand my knowledge on it and kind of specialize myself both in this world and another world (ontologies :D) that i really enjoy.
What's prolog like in 2024? what are you wonderful people doing with it?
thanks from a dumbass :D

Comments (276) 60 threads

Earlier comments
rramadass2 replies#
Though i only know Prolog cursorily it is in my todo list of languages to study. I think it has great value in that it teaches you a different paradigm for programming.

You might also want to look at Erlang which is used in the Industry and would be helpful for your future. Joe Armstrong was originally inspired by Prolog and he conceived Erlang as Prolog-Ideas+Functional/Procedural+Concurrency+Fault-Tolerance. Hence you might find a lot of commonalities here. Here is a recent HN thread on a comparison - https://news.ycombinator.com/item?id=40521585
There is also "Erlog" (by Robert Virding, one of the co-creators of Erlang) which is described as, Erlog is a Prolog interpreter implemented in Erlang and integrated with the Erlang runtime system. It is a subset of the Prolog standard. An Erlog shell (REPL) is also included. It also says, If you want to pass data between Erlang and Prolog it is pretty easy to do so. Data types map pretty cleanly between the two languages due to the fact that Erlang evolved from Prolog. - https://github.com/rvirding/erlog

btbuildem1 reply#
Ha! That explains a lot. I've started looking into Prolog recently, and there were some... familiar echoes in there, reminiscent of Erlang.

But of course, the submarine is like a cigar, not cigar like a submarine.

tannhaeuser1 reply#
Sure, Erlang was prototyped on Prolog because Prolog has excellent built-in facilities for domain-specific languages: you can define new unary or binary operators along with priorities and associativity rules (you can use this to implement JSON or other expression parsing in like two lines of code, which is kindof shocking for newcomers, but comes very handy for integrating Prolog "microservices" into backend stacks), and you get recursive-decent parsing with backtracking for free as a trivial specialization of Prolog evaluation with a built-in short syntax (definite clause grammars) even.

But apart from syntax, Erlang has quite different goals as a backend language for interruption-free telco equipment compared to Prolog.

rramadass2 replies#
In The Development of Erlang Joe Armstrong says "We concluded that we would like something like Prolog with added facilities for concurrency and improved error handling".

See pdf linked here - https://news.ycombinator.com/item?id=40998632

derdi4 replies#
You're reading too much into that quote. This is in a section titled "early experiments". It was an initial goal.

There is a lot of historical connection to Prolog, due to the original implementation, and there are syntactic similarities and non-linear pattern matching and dynamic types and a general declarative vibe, but the actual end result of Erlang's evolution, despite the goal of "something like Prolog", is not very much like Prolog at all. Erlang is a functional language, not a logic language. Prolog is a logic language, not a functional language. General goals like in that quote can change over the decade-long development of a language.

Continue this thread — 4 replies

YeGoblynQueenne7 replies#
Yeah but to be honest, Erlang ended up being not something like Prolog at all.

I think Joe Armstrong was a user here and I interacted with him waaaay way back when I first joined. He's dead now :(

Continue this thread — 7 replies

ristos1 reply#
Prolog is a really interesting language. It's like lisp in that, it's definitely worth learning very well, even if you don't find a use-case for it, because the things you learn help you think about programming in a whole new way.

The prolog community is pretty active. SWI has a discourse group. There's SWISH, CLP(FD/Z), abduction via CHR (a rewrite system) or libraries like ACLP. Prolog is homoiconic, and it achieves it in a unique way, via things like functor/3 and =../2 rather than a macro system. There's growing interest in ISO-standard, pure, monotonic prolog for writing large, clean prolog codebases. SWI is the most mature prolog, but Scryer and Trealla are very active and ISO conformant. Trealla is quite embeddable, particularly in javascript codebases. There's also janus for python, and the community is looking to integrate prolog with LLMs.
Prolog shines for writing bidirectional parsers, NLP, expert systems, abductive reasoning, and constraint logic programming. Pure monotonic prolog has some very useful properties in terms of debuggability, making it useful for large prolog programs. There's also some interesting work in developing pure io (library(pio)). Prolog also has a few different techniques for coroutining, including shift/reset. Markus Triska has a very nice youtube series and book on prolog that's worth watching/reading.
The main downside to prolog is really just that there's a steep learning curve to it that puts a lot of people off and prevents it from gaining more traction, similar to why langs like lisp, haskell, and idris have trouble gaining traction. SWI has a lot of features, but it's also not ISO conformant, and a lot of libraries aren't portable and/or feel very procedural/imperative, which defeats the purpose of prolog. The useful libraries can often be ported to less popular prologs that are more promising, like scryer and trealla. For example, I managed to port ACLP to trealla yesterday without much effort, which is a pretty useful abductive system for writing expert systems or any sort of abductive reasoning.

ristos#
You can also change the search strategy used in Prolog, ie using library(search), supporting BFS and iterative deepening. Tabling is also supported.

Another useful tool for homoiconicity is clause/2:
?- assertz((foo(X) :- append(X, _, [1,2,3]))).
true.
?- clause(foo(X), Body).
Body = append(X, _, [1, 2, 3]).
If you really like Haskell and OCaml's pattern matching, you'll probably really love Prolog. Prolog's pattern matching is much more powerful.

sirwhinesalot2 replies#
Not sure about Prolog itself but Datalog really needs to overtake SQL, it's just so much better.

Related areas like constraint programming are still very relevant.

pfilo84 replies#
Could you explain more or point out some interesting references? I'm currently trying to understand how Datalog compares to SQL and, potentially GraphDBs
sirwhinesalot#
Don't have any interesting references, sorry. My reasoning is mainly one of simplicity and power. In SQL you need to think in terms of tables, inner joins, outer joins, foreign keys etc. whereas datalog you do everything with relations as in prolog.

Not only is it conceptually much simpler, it's also a "pit of success" situation as thinking in terms of relations instead of tables leads you towards normal forms by default.
Add the ability to automatically derive new facts based on rules and it just wins by a country mile. I recommend giving Soufflé a try.
I haven't worked with GraphDBs enough to comment on that.

greenavocado2 replies#
Prolog and Datalog example (they are identical in this case)

    % Facts
    parent(john, mary).
    parent(mary, ann).
    parent(mary, tom).

    % Rules
    ancestor(X, Y) :- parent(X, Y).
    ancestor(X, Z) :- parent(X, Y), ancestor(Y, Z).

    % Query
    ?- ancestor(john, X).
The Prolog code looks identical to Datalog but the execution model is different. Prolog uses depth-first search and backtracking, which can lead to infinite loops if the rules are not carefully ordered.

Datalog starts by evaluating all possible combinations of facts and rules. It builds a bottom-up derivation of all possible facts:
a. First, it derives all direct parent relationships.
b. Then, it applies the ancestor rules iteratively until no new facts can be derived.
For the query ancestor(john, X):
It returns all X that satisfy the ancestor relationship with john. This includes mary, ann, and tom. The order of rules doesn't affect the result or termination. Datalog guarantees termination because it operates on a finite set of possible facts.
Prolog uses a top-down, depth-first search strategy with backtracking.
For the query ancestor(john, X):
a. It first tries to satisfy parent(john, X). This succeeds with X = mary.
b. It then backtracks and tries the second rule: It satisfies parent(john, Y) with Y = mary. Then recursively calls ancestor(mary, X).
c. This process continues, exploring the tree depth-first.
Prolog will find solutions in this order: mary, ann, tom.
The order of clauses can affect both the order of results and termination: If the recursive rule were listed first, Prolog could enter an infinite loop. Prolog doesn't guarantee termination, especially with recursive rules.
SQL is more verbose. The equivalent of the Datalog/Prolog example above is:

    -- Create and populate the table
    CREATE TABLE Parent (
        parent VARCHAR(50),
        child VARCHAR(50)
    );

    INSERT INTO Parent VALUES ('john', 'mary');
    INSERT INTO Parent VALUES ('mary', 'ann');
    INSERT INTO Parent VALUES ('mary', 'tom');

    -- Recursive query to find ancestors
    WITH RECURSIVE Ancestor AS (
        SELECT parent, child
        FROM Parent
        UNION ALL
        SELECT a.parent, p.child
        FROM Ancestor a
        JOIN Parent p ON a.child = p.parent
    )
    SELECT DISTINCT parent AS ancestor
    FROM Ancestor
    WHERE child IN ('ann', 'tom');
This is a more interesting example of how one might use Datalog on a large dataset:

    % Define the base relation
    friend(Person1, Person2).

    % Define friend-of-friend relation
    friend_of_friend(X, Z) :- friend(X, Y), friend(Y, Z), X != Z.

    % Define potential friend recommendation
    % (friend of friend who is not already a friend)
    recommend_friend(X, Z) :- friend_of_friend(X, Z), not friend(X, Z).

    % Count mutual friends for recommendations
    mutual_friend_count(X, Z, Count) :-
        recommend_friend(X, Z),
        Count = count{Y : friend(X, Y), friend(Y, Z)}.

    % Query to get top friend recommendations for a person
    top_recommendations(Person, RecommendedFriend, MutualCount) :-
        mutual_friend_count(Person, RecommendedFriend, MutualCount),
        MutualCount >= 5,
        MutualCount = max{C : mutual_friend_count(Person, _, C)}.
The equivalent Postgres example would be:

    WITH RECURSIVE
    -- Base friend relation
    friends AS (
        SELECT DISTINCT person1, person2
        FROM friendship
        UNION
        SELECT person2, person1
        FROM friendship
    ),

    -- Friend of friend relation
    friend_of_friend AS (
        SELECT f1.person1 AS person, f2.person2 AS friend_of_friend
        FROM friends f1
        JOIN friends f2 ON f1.person2 = f2.person1
        WHERE f1.person1 <> f2.person2
    ),

    -- Potential friend recommendations
    potential_recommendations AS (
        SELECT fof.person, fof.friend_of_friend,
            COUNT(*) AS mutual_friend_count
        FROM friend_of_friend fof
        LEFT JOIN friends f ON fof.person = f.person1 AND fof.friend_of_friend = f.person2
        WHERE f.person1 IS NULL  -- Ensure they're not already friends
        GROUP BY fof.person, fof.friend_of_friend
        HAVING COUNT(*) >= 5  -- Minimum mutual friends threshold
    ),

    -- Rank recommendations
    ranked_recommendations AS (
        SELECT person, friend_of_friend, mutual_friend_count,
            RANK() OVER (PARTITION BY person ORDER BY mutual_friend_count DESC) as rank
        FROM potential_recommendations
    )

    -- Get top recommendations
    SELECT person, friend_of_friend, mutual_friend_count
    FROM ranked_recommendations
    WHERE rank = 1;
Full example you can run yourself: https://onecompiler.com/postgresql/42khbswat
dkarl8 replies#
> Prolog uses depth-first search and backtracking, which can lead to infinite loops if the rules are not carefully ordered

Is this an issue in practice? Most languages can create programs with infinite loops, but it's easy to spot in code reviews. It's been over a decade since I encountered an infinite loop in production in the backend. Just wondering if the same is true for Prolog.

Continue this thread — 8 replies

dmpk2k1 reply#
How does the Datalog approach compare with RETE?

Continue this thread — 1 reply

felixyz#
TypeDb is a practical Datalog-based database system [1] (with a different syntax). TerminusDb is a project in a similar vein [2], but actually an RDF store at its core. If you want to experiment with the connections between Datalog, relational algebra, and SQL, check out the Datalog Educational System. And if you want to jump into the theory, Foundations of Databases (the "Alice book") is very thorough but relatively readable [4]! Oh, and there's a Google project, Logica, to do Datalog over Postgres databases [5].

[1]: https://typedb.com/ [2]: https://terminusdb.com/ [3]: http://www.fdi.ucm.es/profesor/fernan/des/ [4]: http://webdam.inria.fr/Alice/ [5]: https://github.com/evgskv/logica

burakemir#
Mangle is a language that includes "textbook datalog" as a subset https://github.com/google/mangle ; like any real-world datalog language, it extends datalog with various facilities to make it practical.

It was discussed on HN https://news.ycombinator.com/item?id=33756800 and is implemented in go. There is the beginnings of a Rust implementation meanwhile.
If you are looking for datalog in the textbooks, here are some references: https://github.com/google/mangle/blob/main/docs/bibliography...
A graph DBs short intro to datalog: just like the edges of a graph could be represented as a simple table (src, target), you could consider a database tuple or a datalog or prolog fact foo(x1, ..., xN) as a "generalized edge." The nice thing about datalog is then that as one is able to express a connections in an elegant way as "foo(...X...), bar(...X...)" (a conjunction, X being a "node"), whereas in the SQL world one has to deal with a clumsy JOIN statement to express the same thing.

worldsayshi4 replies#
Are there any production ready open source databases using it?
sirwhinesalot1 reply#
Datomic uses Datalog with a weird clojure syntax instead of the usual prolog-like syntax.
worldsayshi2 replies#
Not open source though?

Continue this thread — 2 replies

refset#
Compiling Datalog to SQL with Logica is possibly the easiest path if you need a production ready open source Datalog setup (i.e. choose your favourite managed Postgres provider): https://logica.dev/
networked#
DataScript, Datahike, Datalevin, and XTDB 1.x are open-source. (XTDB 2.x is also open-source but has switched from Datalog to its own query language and SQL.) DataScript, Datalevin, and XTDB have been used in production; not sure about Datahike. All of these databases come from the Clojure community and target Clojure as the primary language. The XTDB team has published a comparison matrix at https://clojurelog.github.io/.

Aside: I write a lot more Python than Clojure, and I wish someone ported Datalevin/Datahike/persistent DataScript to Python. I'd try it as an alternative to SQLite. I suspect with thoughtful API design, an embedded Datalog could feel organic in Python. It might be easier to prototype with than SQLite. There are Datalog and miniKanren implementations for Python, but they are not designed as an on-disk database. PyCozo might be the closest thing that exists. (A sibling comment https://news.ycombinator.com/item?id=40995652 already mentions Cozo.)

cmrdporcupine#
Not sure if "production ready" but it's worth looking at Cozo:

https://github.com/cozodb/cozo
Has a dialect of Datalog + some vector support. Multiple storage engines for backend including SQLite, so if your concern is data stability that seems like a reasonable, proven option.

felixyz5 replies#
Shameless plug: you should check out my podcast The Search Space for a view of the broader landscape of Prolog and logic programming: https://thesearch.space/

I don't publish episodes often but I have a lot of good interviewees lined up :)
In general, I would advice you to look beyond Prolog and explore Answer Set Programming, the Picat language, and the connections between logic programming and databases (SQL, RDF or otherwise). Not instead of Prolog, but in parallel. Prolog is awesome!

overclock351#
ASP is in another uni course of mine ;). I'll check the podcast, thanks
forks#
I'll second the plug: it's an excellent podcast
harperlee#
Good to know there is further content lined up! I’m subscribed and eagerly waiting for it!
agumonkey#
thanks for the thread for allowing to find you and you for making the interviews
duranga1234#
I love your podcast! I wish you published episodes more often!

I particularly enjoyed the first episode, the conversation with Robert Kowalski.

Load more comments