
The Power of Prolog - tosh
https://metalevel.at/prolog
======
triska
Thank you very much for the publicity, I greatly appreciate it!

This book has been discussed on HN about one year ago:

[https://news.ycombinator.com/item?id=14045987](https://news.ycombinator.com/item?id=14045987)

Since then, I have added the following _new_ chapters:

Prolog Business Cases:
[https://www.metalevel.at/prolog/business](https://www.metalevel.at/prolog/business)

Sorting and Searching:
[https://www.metalevel.at/prolog/sorting](https://www.metalevel.at/prolog/sorting)

Cryptography with Prolog:
[https://www.metalevel.at/prolog/cryptography](https://www.metalevel.at/prolog/cryptography)

Engineering Aspects:
[https://www.metalevel.at/prolog/engineering](https://www.metalevel.at/prolog/engineering)

Artificial Intelligence with Prolog:
[https://www.metalevel.at/prolog/ai](https://www.metalevel.at/prolog/ai)

I have also made many improvements and additions to the other chapters.

Also, I have made almost everything available in a public git repository so
that you can track the book's progress and view it offline:

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

It is my sincere hope that you find this material useful, and I welcome all
suggestions and comments.

Also, thank you very much to all readers for the extremely constructive
feedback that I have received in the past year. Your comments have made this
work especially worthwhile.

Enjoy!

~~~
segmondy
I've shared this with anyone who will let me divert the conversation to
Prolog. At work we have the Haskell folks, the Lispers who move everything
towards Lisp, and I'm the one who moves every conversion towards Prolog, then
I send the link to this. :-D

~~~
lispm
The older Lisp folks often have a Prolog integrated in their system...

~~~
madhadron
Actual Prolog. Allegro ships a fully integrated Prolog as part of their
product.

~~~
FractalLP
Now that you say that i think both Allegro and Lispworks both have
that...neat!

------
kccqzy
One of the coolest things I've seen is to use Prolog with CLP(FD) to solve the
7-11 problem. The problem basically says the sum of the prices of four items
is $7.11, and the product is $7.11 too (no rounding); find the prices of these
four items.

This can be solved in two lines of code that gives the (unique) solution in a
second. Not even my expensive Mathematica can do this!

    
    
        ?- use_module(library(clpfd)).
        true.
        
        ?- Vs = [A,B,C,D], Vs ins 1..711, A * B * C * D #= 711000000, A + B + C + D #= 711, A #>= B, B #>= C, C #>= D, labeling([ff, down], Vs).
        Vs = [316, 150, 125, 120],
        A = 316,
        B = 150,
        C = 125,
        D = 120 ;
        false.
    

Another great thing Prolog is good at is type inference. After all, type
inference, in its simplest form, is just syntax-directed constraint generation
and then using unification to solve constraints—exactly what Prolog gives you
by default. You can write a type inference engine for simply typed lambda
calculus in Prolog in 10 minutes. Google used to have a project to do type
inference for Python written in Prolog, although they've since [switched
away]([https://github.com/google/pytype](https://github.com/google/pytype)).

~~~
triska
Hah! I used exactly this example to motivate the arbitrary precision CLP(FD)
implementation, published as _The Finite Domain Constraint Solver of SWI-
Prolog_ , FLOPS 2012, LNCS 7294:

[https://www.metalevel.at/swiclpfd.pdf](https://www.metalevel.at/swiclpfd.pdf)

The observations on type inference are also spot on. The project you mentioned
was previously discussed on HN, but the page is no longer available:

[https://news.ycombinator.com/item?id=12108041](https://news.ycombinator.com/item?id=12108041)

~~~
kccqzy
Oh you implemented this CLP(FD) and wrote that paper! Thanks a lot! My 7-11
example is probably because I first saw it in your paper then.

------
restalis
I hated this language (and I'm saying it knowingly, despite the fact that this
is most definitely a Prolog loving group). I found its working model difficult
for me and the ROI quite low. I wanted to make my critique a bit constructive
though and, before spitting out something of my own, I decided to look if
there's already anything available in this regard. I think Andre Vellino puts
it quite well (or at least better than I cold) in his "Prolog's Death"
blogpost[1]. I invite you to have a look at it. Leaving aside Prolog's
language design decisions, logical languages in general may be for now just a
bit precocious, something not meant to flourish in our time. However, the
computing hardware evolves and with it getting more complex and harder to
predict the imperative paradigm being better fit for the underlying physical
architecture becomes less and less true with every passing day. Although I
can't say I'm thrilled about it, in time the logical languages may become the
better offer for the average Joe looking for quick results, something closer
to what for now Python is.

[1] [https://synthese.wordpress.com/2010/08/21/prologs-
death/](https://synthese.wordpress.com/2010/08/21/prologs-death/)

~~~
lolc
Quote from the link: "The most confusing thing about Prolog is that, whatever
algorithm you implement with it must be on top of the built-in ones, namely
depth-first search, and unification (and only using recursion rather than
iteration). "

When I discovered that during my studies I decided that Prolog is not for me.
First it looks neat for toy problems and then you're fighting the solver until
you give up.

------
simonraikallen
Its so nice to hear Prolog is alive and well. While at university I spent
quite some time wrangling with it and grew to love it. So much problem solving
smarts built into the runtime.

Here is my crowning achievement from back then in 1993 - a genetic programming
simulator that evolved ants to follow pheromone trails in pure prolog.

[http://www.cs.cmu.edu/Groups/AI/areas/genetic/gp/systems/gp_...](http://www.cs.cmu.edu/Groups/AI/areas/genetic/gp/systems/gp_pl/gp.pl)

Enjoy.

~~~
w0m
Nerd.

In 2005 I used Prolog to a solved pathfinding for competive maps in CS 1.6
based off weighted examples form interviewing a 'professionals' calls, even
had a plugin architecture to extend each map, though it only worked well for
Dust2 before I had to present. Way more practical. Cough.

That was fun. Now I want to find the code...

------
pjc50
Prolog: just say no.

(To explain the joke, one of the main problems with Prolog is that solutions
which cannot be unified just emit a "no" with no further explanation, making
large Prolog setups hard to debug)

~~~
tom_mellior
I think the usual (and funnier) version of that joke is:

    
    
        Q: How many Prolog programmers does it take to change a lightbulb?
        A: no

------
jlarocco
This is a nice coincidence.

A few weeks back a guy at work gave away a box of old computer books, and I
picked up several on Prolog and logic programming.

I've been reading through an ancient edition of "Programming Prolog", which is
good, but I've had a hard time finding modern code samples. The code in the
book mostly works, but I've seen some weird behavior that I suspect is due to
language changes. It'll be nice to have these up-to-date examples using modern
idioms.

------
pjmlp
One of my favorite languages, pity that is has had even harder time than Lisp
getting mainstream acceptance.

~~~
tabtab
Let's face it, procedural is just plain easier to debug because you can more
easily split it into digestible and dissect-able chunks: divide-and-conquer.
Perhaps functional and logical CAN readily have such features, but nobody
either figured how, or have not figured out how to explain how to do
dissection to normal people. (This is sometimes a criticism of SQL also, but
the added WITH clause helps break up big queries into multiple smaller ones.)

For example, with a procedural loop you can stick a debug statement in the
middle to look at just about anything:

    
    
      while (x=foo(y,z)) {
        a = doStuff(x, z);
        console.write("x={?},y={?},z={?},a={?}", x, y, z, a);
      }

~~~
chriswarbo
No idea why you think functional programming can't do printf debugging. Even
pure languages like Haskell have `unsafePerformIO` (or wrappers like
[https://hackage.haskell.org/package/base-4.11.1.0/docs/Debug...](https://hackage.haskell.org/package/base-4.11.1.0/docs/Debug-
Trace.html) ).

Also functional programming heavily encourages splitting up code into
digestible chunks (they're called functions ;) )

~~~
sakuronto
I guess humans, being the temporal creatures we are, have an easier time
debugging procedural programs because they have a "story", an expected
sequence of "events" (calls, reassignments, etc.), that naturally goes with
the program. Functional programming inherently obscures that.

~~~
YeGoblynQueenne
Prolog on the other hand has a very clear imperative reading, that fits
alongside the declarative one. In fact, this is probably one reason why many
programmers used to imperative languages find it hard to pick up Prolog and
run with it - they get distracted by the imperative reading.

On the other hand, that makes it much easier to debug code, by thinking along
the lines of "p/2 is called after p/4" or even "p/2 returns A that is passed
to p/4" (even though strictly speaking predicates don't "return" stuff).

------
guuz
Very good material. Prolog (or the ideas behind it) really needs a resurgence.

~~~
arca_vorago
It's still going strong in the industrial side of things (like SCADA). You
just don't hear much about it.

~~~
FractalLP
I've never heard of Prolog alongside SCADA. Can you be more specific? Like in
a plant or what?

~~~
arca_vorago
You know, I'm not sure where I got that from. Maybe I was confusing prolog
with the ladder logic, or other languages from IEC 61131-3? I'm really not
sure... but after some duckduckgoing I've come to the conclusion I was wrong
in my previous statement... sorry.

~~~
FractalLP
No problem. Ladder logic and C I can definitely see, but SCADA would have
blown my mind :)

------
peter303
Prolog was one of hot A.I. prospects of the 1980s. It could be a way to build
an expert system. Japanese fifth generation computers were supposed to,run it
fast.

Then A.I. boom fizzled. Neither the first or last business cycle.

~~~
enkiv2
The fifth generation project didn't actually use prolog, but instead a custom
prolog-like language.

However, there's still work being done adjacent to 5G using real prolog, by
people who thought it was an interesting idea: [https://github.com/bitlaw-
jp/the-constitution-of-japan](https://github.com/bitlaw-jp/the-constitution-
of-japan)

Prolog is still used in the development of expert systems, though when those
systems are shipped, they have often been rewritten in an imperative language
based on a Prolog prototype.

The fifth generation project, from what I understand, died because of a
dedication to custom hardware using already-obsolete fabrication tech --
mid-70s flipflops-on-IC tech over late-70s microprocessor-on-IC tech, wire
wrap, etc. There was an inability or unwillingness to iterate on original
committee designs. By the time it folded in 1998, everything involved looked
like stone knives and bearskins. Those boxes wouldn't have been able to run it
fast by 1980 standards.

------
Jedd
I recall at college in 1989 our lecturer had brought in a chap who'd done an
entire airline baggage management suite written in prolog (turbo prolog, to be
more accurate). The demo we saw was absolutely gorgeous -- real time updates
on-screen to changes in baggage locations elsewhere (in the system). This was
on i386-equivalent machines, before anyone gets overly nonchalant. He
explained that he'd been up against two competing tenders - one in COBOL, the
other in C - both higher priced and longer delivery times.

Nonetheless, I still never really properly grokked prolog, as much as I tried.
I feel my brain had already been wired away from declarative languages.
Perhaps a poor cop-out.

------
andromeduck
Prolog loses a lot of its magic when you realize it's just DFS the language.

~~~
hellofunk
C loses a lot of its magic when you realize it's just memory but with
syntactic sugar.

~~~
triska
A fun fact that may appear surprising at first: In contrast to Prolog, C is
actually _not_ Turing-complete!

Here is more information:

[https://cs.stackexchange.com/questions/60965/is-c-
actually-t...](https://cs.stackexchange.com/questions/60965/is-c-actually-
turing-complete)

In C, you can only represent an unbounded tape if you assume the existence of
an unbounded _stream_ , i.e., in a so-called _hosted_ implementation of C
where unbounded streams are available. But unbounded streams cannot be
implemented in freestanding C, even if unlimited memory were available!

------
dontwantai
I imagine that there must be some system similar to prolog but with a
probabilistic model of inference, for example ground rules could be sorted by
statistical properties to accelerate inference. Just like machine learning
trees select features for classification (perhaps using cross-entropy
minimization).

Edit: I found Journal of Machine Learning Research 7 (2006) 307–342, Kernels
on Prolog Proof Trees: Statistical Learning in the ILP Setting

~~~
enkiv2
I wrote something like this, based in part on ideas from PLN:
[https://hackernoon.com/mycroft-a-predicate-logic-language-
ov...](https://hackernoon.com/mycroft-a-predicate-logic-language-overview-
post-mortem-e357fe80d53)

------
xvilka
From my experience the hardest part is interaction with other programs and
libraries. Still cannot make pipes work in
[https://github.com/XVilka/r2pipe.prolog/blob/master/r2pipe.p...](https://github.com/XVilka/r2pipe.prolog/blob/master/r2pipe.pl)

~~~
doublec
What's the problem you're having with it? I think this was discussed on irc
recently? This was the example I gave of using process_create which works:

    
    
        process_create('/bin/cat',
                       [], 
                       [stdout(pipe(Out)),stdin(pipe(In))]),  
        write(In, "hello"), nl(In), close(In), 
        read_line_to_codes(Out, Codes).

~~~
xvilka
Well, I need to keep both pipes open during the "session", since usual radare2
session involves hundreds of commands and their output. Opening a new pipe and
process every time is a wrong way to go in my opinion.

~~~
doublec
You should be able to open the pipes at the beginning of the session, and
close them after, passing the pipe variables around as needed. Prolog wouldn't
be any different to other programming languages there. What errors are you
getting? Maybe post to the swipl mailing list?

~~~
xvilka
I will send a message to mailing list then, thanks for the suggestion.

------
ghosthamlet
Practical logic programming in Clojure :
[https://github.com/clojure/core.logic](https://github.com/clojure/core.logic)

A modern logic programming language:
[https://github.com/mcsoto/cosmos](https://github.com/mcsoto/cosmos)

~~~
hellofunk
Core.Logic is a miniKanren implementation which is quite different from Prolog
(smaller and ultimately less powerful, but cool nonetheless). Many/all
miniKanren solutions also work in Prolog, but the vice-versa is not true.

------
orionblastar
[https://en.m.wikipedia.org/wiki/Visual_Prolog](https://en.m.wikipedia.org/wiki/Visual_Prolog)

Turbo Prolog is now known as Visual Prolog. Just for those who wondered what
happened to it and might want to ude it.

------
pdkl95
Prolog is crazy-making and awesome in all the right ways. For some problems,
it can be _very_ concise.

[https://swish.swi-prolog.org/p/xkcd287.pl](https://swish.swi-
prolog.org/p/xkcd287.pl)

------
ausjke
used prolog many years ago, how is it now? is it evolving?

it IS the language for expert systems, curious if it can be the best language
for general AI developments.

Just installed prolog under ubuntu and vscode has a plugin for it, all look
good, will play with this more.

------
westoncb
The core ideas behind Prolog have the feel of something discovered rather than
invented, and I bet we'll see significant new forms of it yet.

My first encounter with it was while taking a _Principles of Programming
Languages_ course that I hadn't been attending regularly... We had a test on
Prolog four days out and I hadn't learned a bit yet. I found a couple books in
the library—one of which was excellent—and was soon so absorbed by it that I
learned everything I needed out of sheer interest and got a perfect score on
the test.

Some six years later—the whole time not having touched Prolog or even thought
about it that I can recall—I got an idea for a programming language. It would
be an attempt to model 'schemas' in the human brain. Programs written in it
were supposed to reflect human conceptual structure. Once you defined the
concept for something, let's say a chair, you could ask it to generate
instances. It was in part going to be a language designed from the ground up
for procedural content generation.

There were some promising things about it (like a very concise/natural way of
defining 'analogy'[0] and other aspects of thought), but ultimately, a couple
years after coming up with the idea, I picked up a copy of _The Art of Prolog_
and read the first few chapters (for general edification, and so that I'd be
more aware if it were applicable to something I was working on). By that
point, I felt pretty convinced that my language idea would only be
superficially different from Prolog, and that most of the really interesting
ideas were already captured by that language.

One up side to the project was that, after coming up with a pretty detailed
plan for how the runtime would work, I decided to write this 'abstract visual
debugger' to help me build it (the runtime would involve loads of complex data
structure interactions that prior experience taught me were much easier to
wrangle if visualized). It still seems like a promising project to me, and I
work on it when I get free time. Video here:
[http://symbolflux.com/projects/avd](http://symbolflux.com/projects/avd)

I also still have a bunch of random notes/ideas I took down about the language
idea I had. Warning—I was pretty excited and they sound a bit like that
ravings of a madman: [http://symbolflux.com/IntellAgent-
ideas.txt](http://symbolflux.com/IntellAgent-ideas.txt) I also wrote an ANTLR
grammar for it, but that's probably not as entertaining.

[0]

    
    
      Analogy: 
      +{original: Type, analogy: Type}
      -{
         
         Equivalence{Particularization{Generalization{original}}, analogy}
       }
    

Equivalence etc. are all relation constraints; the run-time would discover a
value for 'analogy'. The idea is to generalize whatever the thing is
('increases generality of the attribute Types' —from my notes), fill in values
of some params to particularize, and have the constraint held that the
discovered analogy is Equivalent to the original (sharing the same structure,
which had a definite meaning in the context of the language).

