Hacker News new | past | comments | ask | show | jobs | submit login
Learn Prolog Now (learnprolognow.org)
289 points by febin 7 months ago | hide | past | web | favorite | 70 comments

Datalog is a form of prolog, used currently by a database called datomic as it's query language. If you wanted to play with datalog, the best way is to do the free tutorial at www.learndatalogtoday.org you don't need to anything about datomic or clojure in order to do the tutorial, and I found it really helpful to get an idea of how it would be really helpful for certain types of queries, compared to an analogous query in SQL (which I also like btw...)

[Edit] - funny, someone just posted this other tutorial to HN too, haven't done it yet but looks fun and educational, it's a murder mystery! https://xmonader.github.io/prolog/2018/12/21/solving-murder-...

All my upvotes, it's criminal how under hyped Datomic is

Hyperfiddle is a paradigm shift on the front end too, using the same concepts, imagine real time GraphQL on steroids where the query doesn't need a horrible SQL translation on the backend and that doesn't even begin to cover it, no worrying about multiple round trips, SQL injection gone, cache invalidation solved, supports recursion, nested data

Everyone outside of Clojure/Datomic should be looking in for things to steal

Datomic's popularity is constrained by the decision to make it closed source commercial software. That's not a knock. It's not saying Datomic is not worth the money. Profitability in exchange for popularity is a very reasonable decision.

The decision not to play around with the free version of proprietary software is also reasonable. Vendor lock-in is a trade off many developers are not interested in making.

There now an open source alternative to Datomic suitable for small applications: https://github.com/replikativ/datahike


Here's an instructive post from Frank McSherry on building a simple datalog engine in Rust (which I think might currently be used in Rust's new borrow checker?): https://github.com/frankmcsherry/blog/blob/master/posts/2018...

Did you mistake it with Chalk[1]? Unlike DataFrog it is not too basic, actively developed and aimed to be used in Rust compiler itself.

[1] https://github.com/rust-lang-nursery/chalk

I don't think I'm confusing it with Chalk; note that Datafrog is, like Chalk, hosted in rust-lang-nursery and sees ongoing development. IIRC Chalk is more intended to serve the trait system, rather than the borrow checker as mentioned in Frank's post. Of course, I have only a passing idea of what all these experimental components are being aimed at (and it's possible that I'm confusing Datafrog with another one of them, like, say, Polonius).

There is also more modern Power of Prolog[1][2]. Another interesting language is ProbLog[3] - Probabilistic Prolog, seems used in bioinformatics.

[1] https://www.metalevel.at/prolog

[2] https://github.com/triska/the-power-of-prolog

[3] https://dtai.cs.kuleuven.be/problog/

Also, there is MiniZinc: https://www.minizinc.org/

Wow. I wish this existed when I was in middles school, trying to write science fair project in prolog. It sent me down an academic rabbit hole that was way above my depth of knowledge. And the books I could find were really dry academic oriented. But I powered through and wrote a prolog program to help identify poisons.

A friend of mine wrote a Chrome extension for better styling: https://chrome.google.com/webstore/detail/learn-prolog-now-e...

Why? No, really, subjectively Prolog looks lovely to me, but sort of "Chapter 0" explaining why should people learn Prolog and how they can apply it practically could make an awesome addition.

The more areas of knowledge one has some familiarity with and the more often one is able to recognize that most of the daily adversities we face are just random incarnations of well known general problems (sometimes you'd better ignore the "academic" solution due to local circumstances, but not always).

Many time a programmer will be faced with a problem which solution is to collect a set of facts and ask arbitrary questions against those. Unless one has had some exposure with prolog, one may not recognize this problem and may start designing a custom inferior system, either from scratch or based on unfit tech.

Real life example:

I worked once for a very respectable company where we had been given the project of devising a system that would assess the trustworthiness of accesses to some sensitive application based on a ever expanding set of data collected about users, their devices, locations, and so on. We wanted the rules governing access to be defined and refined with time by the security department. So I thought that would be a good fit for some prolog-like database and looked for one; and I could actually find one that checked all the boxes: usable as a library from C++, could update the dataset and the rules without interruption, compiled the queries down to machine code to withstand our gazillions of queries-per-secs, developed indoors (to counter the NIH syndrome), and instead of FALSE the lib would also return some metadata that could be used to produce a meaningful error message.

A prototype was build in 2 weeks or so, involving 1.5 person, one of which had never used prolog before. Had never used it but knew about it. Otherwise, you can be certain that a very different path would have been taken: to hire a whole team of engineers to develop from scratch and for a very long time their very own capability system/data storage system/error reporting system that would have been less flexible and much slower, required restart for reconfiguration, etc.

You can be certain of it because that's the path the company actually decided to follow, to the great benefit of those involved, who've all been rewarded with a promotion for such an undertaking :-)

Because Prolog bends your brain and getting your brain bent is fun. :) In the real world there are few applications of Prolog. Part of the reason is that Prolog doesn't mesh very well with functional programming constructs which are very popular in data processing. Another part of it is that the execution model doesn't match many real world problems. For example, in a document retrieval system you might want to find the 10 documents that most closely match an input query. Describing that as a constraint programming problem (Prolog excels at those) is not easy.

Yes. I'd love to know more about real world use cases.

Edit: Found some relevant threads and links: https://news.ycombinator.com/item?id=9248107 https://www.youtube.com/watch?v=G_eYTctGZw8

As an abstraction, think of a Prolog program as a collection of facts and running a Prolog program as a query against those facts. Or basically a Prolog program as a static (or read oriented) database. Or describing a set of rules.

Rolling back, as a declarative language in the database abstraction, the programmer can run queries with verbs that model the domain instead of SQL's generic WHERE, FROM, SELECT, etc. The price is that all facts have only three parts...like RDF [1] so maybe the programmer comes out ahead on design of the data relations.

Not all workloads are close to read-only databases. But some are, and Prolog allows writing such programs without the low level abstractions of the relational model using higher level DSL's.

[1]: https://en.wikipedia.org/wiki/Resource_Description_Framework

>> The price is that all facts have only three parts...like RDF [1]

Prolog "facts" can have any number of arguments. The only way I can think of reconciling Prolog facts with your comment about "only three parts ... like RDF" is that Prolog facts are first-order predicates which consist of a predicate symbol, a vector of arguments and a pair of enclosing parentheses. Is that what you meant?

How does storing facts in the source code instead of a database make any practical sense? I mean I can hardly imagine a real-life scenario where the number of facts is so small.

Facts are both data and "source code". It's a fact that a user with id=0 has name=Bob. It's also a fact that the sqrt(x^2)=x or the http response code when a resource isn't found is 404. Some of those belong in databases, some definitely don't.

This isn't a real life example, but illustrates the sort of facts that are difficult to maintain in a BCNF relational database...and are still difficult to query in a non-BCNF relational database.

  Paper covers Rock
  Rock crushes Scissors
  Scissors cut Paper
In Prolog we might encode that:

  wins(paper, rock).
  wins(rock, scissors).
  wins(scissors, paper).

  loses(X,Y) :- wins(Y,X)
Relational databases are good for storing context-free facts. In table T, the interpretation of row R1 is independent of the contents of row R2.

A practical real-life scenario for Prolog might be a "help wizard." The next step depends on what steps we have already tried (and not tried) and other kinds of state. The next step can be expressed as a Horn Clauses.

  X /\ Y /\ NOT Z -> Z
  NOT B /\ NOT W /\ X /\ Z /\ A /\ Q -> M
If the Prolog and the Horn Clauses look a bit like regular grammars, writing compilers is another area where Prolog has been applied historically. The first version of Erlang is an example, and some of Erang's design made more sense to me after learning a little bit of Prolog. But I am into learning mostly useless subjects.

Pretty much what I came here to ask. I remember learning a bit of prolog about 20 years ago at University, but even then my impression from the instructor was that it was not used much outside of some limited academic settings. I seem to recall from that same instructor that most use cases for prolog had been subsumed by Lisp.

Yes. I'd love to know more about real world use cases.


More than 200 million airline bookings, 850 million total (travel and hotel) bookings per year. They are known to run their airline reservation system on Sicstus Prolog, though I don't know how well that is publicly documented in writing.

Why learn something new? To increase your knowledge. If that's not reason enough then nothing else is.

That's an ungenerous interpretation of the question. Consider this variation: Why learn Prolog instead of spending the finite commodity of time to learn something that may be equally engaging on an intellectual level but also more practical?

To me, that variation is implicit within such a question.

Edit: I'm reasoning from the HN comment guidelines [0]: "Please respond to the strongest plausible interpretation of what someone says, not a weaker one that's easier to criticize. Assume good faith."

This guideline is in fact a restatement of one of the fundamental principles of reasoned discourse, the principle of charity [1]

[0] https://news.ycombinator.com/newsguidelines.html

[1] https://en.wikipedia.org/wiki/Principle_of_charity

>> Consider this variation: Why learn Prolog instead of spending the finite commodity of time to learn something that may be equally engaging on an intellectual level but also more practical?

I have to ask- like what? Are we talking about the next javascript framework, here, or about, I don't know, modal logics or category theory?

I know a guy who got an internship at ARM during a PhD in modal logic, so, far as I can tell, modal logic is both intellectually engaging and also practical, as in useful, in practice (to be blunt: to land you a job). Is that what you are talking about?

Sure, that seems a good example, and brings up a point I didn't mention: practicality can be a very contextual quality.

Generally though I think it's fair to interpret any question of "why should I bother learning X" not as a statement that nothing should be learned unless there's a direct benefit, but instead as the question "what are the practical applications of X". I think most people here would agree that learning for learning's sake can be fruitful & rewarding, so there's no reason to assume otherwise in response so such a question.

I don't understand what you're saying. If the OP's question was "what are the practical applications of X", then obviously he didn't consider it that learning for the sake of learning is useful.

Some people don't like to learn just for the sake of learning. So, I find it reasonable for someone to want to know the practical applications of something.

Maybe they prefer to learn through building something. Maybe they're working on something and are interested to know if Prolog could help them with their project.

Why say the OP obviously didn't consider learning for learning's sake useful? I see nothing obvious there. Asking for practical applications does not logically preclude the OP also appreciating learning for learning's sake, and I see nothing else in their post to imply their stance on it one way or the other. As such I choose the more charitable interpretation.

Well, it's christmas. Although I'm an atheist, HN has put on its holiday suit and I don't feel like pressing this point any further. My apologies to the OP and to yourself, if my earlier comment sounded too curmudgeonly. I'm really the Grinch that stole Christmas, so don't mind me :)

no worries, these are all interesting things to discuss, and i enjoy doing it. atheist myself too :)

But why should I learn it over the zillion other things that I'm trying to learn? Especially since I have only so much time for non-practical skills.

Prolog has been around for a long time (in computing terms). It will probably be around a long time from now (in programming terms). Prolog won't bit rust sitting in your toolbox in the same way that ASP, Flash, and MacOS did.

The thing that intrigued me the most about Prolog was that true and false are not opposites. True means it could prove it, but false means it couldn’t prove it in time, not strictly necessarily really false as in not true. Thinking about that distinction, that you can have a language where the default logic can’t be used for Boolean algebra, blew my mind when I was in college and has been fun to ponder ever since.

Sounds more like true and null? Or does it not definitively disprove things?

The parent is mistaken. A "false" answer definitely means that no (further) solution exists. You can ask for time or depth limits in practical Prologs, but in basic standard Prolog "false" doesn not mean "could not prove it in time".

Of course some things cannot be disproven, and in those cases (again, if you don't request otherwise) you will get nontermination.

Prolog uses the closed world assumption: if something cannot be proven, it is considered false.


I dived into prolog this year, and I really liked it. However, I didn't find a very active community to answer questions. The lack of energy in the community, and my wondering where I could use prolog for a practical application, tempered my enthousiasm, and I switched to learning something else (category theory).

What sources do you have to learn category theory?

I watched Bartosz Milewski's videos https://m.youtube.com/playlist?list=PLbgaMIhjbmEnaH_LTkxLI7F...

The pdf generated from his blog is also interesting :


These are the best resources I found about the subject.

Videos are awesome, I started watching them and ended up binge watching!


Checkout the prolog channel on freenet

For those wanting to kill the "learn logic programming" and "learn a golfing language" birds with one stone, check out:



I've study a super-little-bit prolog at university time but I do not really understand it... I still have to understand "why prolog?" at all but perhaps sooner or later I'll try to review it a bit with this site-book :-)

Prolog is great for a thing called constraint satisfaction. You define a bunch of predicates, which may or may not have meaning in the implicit dependencies, and then the language is able to extract logical relationships between those atoms in these defined predicates. You might have had an instructor who himself hadn't really mastered the language, or maybe he didn't grok it - because it's very beautiful and intuitive when its laid out properly. It was the language I picked up the fastest in all of my coursework, just super elegant and bare bones.

OT, but another point to note is that the original Erlang VM and interpreter was implemented in Prolog, which (because of Joe Armstrong's affinity for the language) might be why there are so many subtle syntactical similarities between the two languages.

This tutorial does a pretty good job at first glance, but I feel like there could be some more sophisticated examples that more concretely illustrate why it's such a powerful technique to use

Well I (not really) "learn" for a side course just to get some extra credits (I do not know if this mechanism exists outside western EU) so... I can practically say that I only have seen it's syntax and play with it at a so ignorant level that I do not really understand it's motivations...

Constraint satisfaction to my eyes seems a bit of an obscure concept that is substantially present in any functional programming language, however since prolog is still there and popup regularly I understand that it's me that miss something and so I'm curious and perhaps sooner or later I'll try to reread docs and try to really understand while keep it a bit down in my priority list...

Yes, I remember that Prolog was suppose to be good with semantic applications, but I thought Lisp was similarly (if not quite as well) suited along with being better in other respects. Though it is interesting (as I learned from another comment) that a variant of prolog is used as a database query language. It does seem like a very nice fit.

I was going through this recently because my brother is going through the CS program that I went through, which is the only time I've encountered anyone mention Prolog. I still can't really envision how to create comprehensive systems in this, but it seems the logic paradigm could be applied to some really useful new areas that it hasn't reached yet, similar to how the influence of functional languages is pretty much expected for any trendy new language today (Rust, ES6).

I think it helps to think of Prolog as something similar to SQL. See, for example, https://stackoverflow.com/questions/2117651/comparing-sql-an....

It doesn't really help to think that way. The accepted answer to that StackOverflow question sounds very much like the poster didn't really know what Prolog is (and possibly confused it with Datalog).

Here is code to append two lists in Prolog:

    append([], Xs, Xs).
    append([X|Xs], Ys, [X|Zs]) :-
        append(Xs, Ys, Zs).
You can use this as follows ("?-" is the user input prompt, equations are the system's answers):

    ?- append([a,b], [c,d], Zs).
    Zs = [a, b, c, d].

    ?- append(Xs, Ys, [a,b,c]).
    Xs = [],Ys = [a, b, c] ;
    Xs = [a],Ys = [b, c];
    Xs = [a, b],Ys = [c];
    Xs = [a, b, c],Ys = [].
How would you express the notion of lists in SQL? How would you express the notion of appending two lists? And how would you express the notion of searching for all possible pairs of lists that, when appended, yield the list [a,b,c]?

> the influence of functional languages is pretty much expected for any trendy new language today (Rust

Rust is barely influenced by functional languages.

>Rust is barely influenced by functional languages.

That is arguable. Rust supports and in a lot of ways prefers functional solutions for problems, for example the iterator trait in std and a gazillion similar library APIs. Functional programming works very well with Rust's type system.

for expert system prolog is the king

Yes. But others (like Haskell) aren't much behind.

I quite enjoy watching successive generations of programmers rediscover prolog in particular and rule-based programming in general. It's well worth learning even if you never really use it, because it expands your understanding of the art.

I tried swipl prolog and enjoyed it but poor PostgreSQL support scared me away. Any prolog developers have any advice? I really like prolog but need an implementation with good db support for specifically Postgres but haven’t found anything.

You don't need SQL if you have Prolog. Prolog itself can store and retrieve all your data, except that data is also your program at the same time.

For instance, see:

Can I replace a LAMP stack with SWI-Prolog?


That raises the questions of how competent are the atomicity of changes, persistence, and speed and memory optimizations implementations of your Prolog interpreter?

And, since those are not usual goals of an interpreter, I would guess "not very competent" for at least the first two with high certainty.

It also raises the question of whether Postgres has a good Prolog plugin. This one looks more likely to be useful.

This is a really great answer, thank you.

Cheers. Note also that you can relatively easily move all your SQL tables to Prolog by exporting them as text files with Prolog facts of the form:

  <table_name>(<column 1, row 1>, <column 2, row 1>, ...., <column n, row 1> )
  <table_name>(<column 1, row m>, <column 2, row m>, ...., <column n, row m> )
So each table becomes a predicate with the table name as its predicate symbol ("functor" in Prolog), the number of the columns in the table as its arity (the number of arguments of the predicate) and where each row of the table is a separate clause of the predicate.

Many tables exported this way will not be necessary any more, particularly those ubiquitous tables used to map other tables' keys between them ("Customer_ID_Ticket_Id" etc) and in most cases primary key fields will no longer be necessary and so on- but you can move all your data to Prolog, with very little change, is what I'm trying to say.

Mer' Christmas :)

Nice! That gives me faith for using it for my personal projects. I enjoyed erlang when I programmed in it in my fledgling days and I like the tenseness of the prolog-influenced languages. Having a very easy way to port to a platform(or off, sometimes) is certainly a valid concern of mine when choosing my tooling. Merry Christmas to you as well :)

Prolog is a language I have fond memories of but haven't touched in a long time. How applicable is it outside of academia given all of the alternatives?

So for the end of year 2018, is there still people using Prolog in profession field instead of academic?

This is the website I used to learn Prolog and all I can do is to highly recommend it

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact