480 points · by tosh · 8y ago · 158 comments
This book has been discussed on HN about one year ago:
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
Sorting and Searching: https://www.metalevel.at/prolog/sorting
Cryptography with Prolog: https://www.metalevel.at/prolog/cryptography
Engineering Aspects: https://www.metalevel.at/prolog/engineering
Artificial Intelligence with Prolog: 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
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!
One related workplace anecdote that a former fellow student told me: He was working on a rule-based medical recommender system, and he recognized that Prolog was an excellent fit for this project. When he first suggested that the team switch to Prolog, they were very skeptical. But someone high up in the chain was a great fan of Prolog and approved this suggestion. A few weeks later, they had completed the implementation, and the Prolog-based solution was running. My colleague told me that, a few months after that, the whole team regarded Prolog as the only viable solution to all further projects from then on!
Hm, there is such a thing as the right tool for the job. If all their jobs were very similar that makes sense, otherwise, not so much.
Are you aware of the fact that inside every Windows NT installation there was a Prolog engine to help with network configuration?
http://web.archive.org/web/20040603192757/research.microsoft...
And what kind of reaction are you getting? As I just wrote elsewhere, I don't think this is useful for complete Prolog beginners to learn the language or even get a feel for it. Has anyone you sent this to come back with "that's neat, I read the first N chapters and have just written my first Prolog program on my own"?
What are strong cases to use Prolog/Haskell these days? :D
ebony and ivory / live together in perfect harmony
etc
In general, the AI chapter is what I am currently working on most. I mean not "only" on the actual content, but on the applications I want to present in this chapter.
Anton Kochkov has recently motivated this chapter via a dedicated issue for AI/ML applications of Prolog, and I invite you to track its progress at:
For your machine learning section, you might want to consider discussing Metagol [1], a modern ILP system that can learn recursive theories and perform predicate invention.
The core Metagol implementation is tiny and relies on a meta-interpreter (the technique is called Meta-Interpretive Learning). It is a radically different approach to previous ILP systems but much simpler and easier to understand. It should be interesting to anyone who wants to do machine learning with Prolog.
____________
Regarding companies that use Prolog, here are a few examples:
A third of all airline traffic is handled by systems that run SICStus Prolog:
https://www.sics.se/projects/sicstus-prolog-leading-prolog-t...
A large portion of the New Zealand stock exchange is powered by Prolog:
https://dtai.cs.kuleuven.be/CHR/files/Elston_SecuritEase.pdf
Oracle uses Prolog in the JVM specification:
https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-0-pr...
IBM has used Prolog for natural language processing in Watson:
https://www.cs.nmsu.edu/ALP/2011/03/natural-language-process...
RedPrairie uses SICStus Prolog for optimization tasks.
Prolog is used for voice processing on the International Space Station.
http://smallcultfollowing.com/babysteps/blog/2017/01/26/lowe...
But are those systems responsible for all the I.T. problems that are plaguing the industry?[1] (I've been under the impression the issues were primarily with COBOL/mainframe systems, but wasn't aware Prolog was so widely used by airlines).
[1] https://www.google.com/search?hl=en&q=airline%20computer%20f...
One that was new and interesting to me is that gerritcodereview (by Google) is written in Prolog.
https://gerrit-review.googlesource.com/Documentation/prolog-...
So, yes, I agree: Prolog may well be suitable for this! In practice, for statistics-based methods, the core logic will likely be carried out by dedicated hardware which you may have to program in its own language. Prolog may still play a part also with such approaches, for example to generate test cases and correctness certificates, and as a rule-based safety measure to prevent certain situations from happening.
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://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://github.com/frankmcsherry/blog/blob/master/posts/2018...
via
Edit: Here's a solution in Haskell. I've been paid to program in both Prolog and Haskell, but it was a while ago; my knowledge of both languages is very rusty.
main = putStrLn $ show [(a, b, c, d) | a <- [1..711], b <- [a + 1..711],
c <- [b + 1..711], d <- [711 - a - b - c], c <= d, a * b * c * d == 711000000]https://gist.github.com/calroc/603ed919bc814ccee10c1b3df6142...
> Do you think this might be more useful as a module to solve logic puzzles, rather than as a complete language by itself?
I was thinking about it this morning and I came to the conclusion that Prolog really is AI. They did it. We have AI already and most of us just failed to notice. The Unification algorithm at the heart of Prolog (I'm not an expert!) is pretty much what your brain does when you solve logical puzzles and problems. We have a machine that can think.
The way I think of Prolog is as a super-calculator that can be applied to a huge range of problems and tasks. (One thing to be aware of is that if you have a Prolog-shaped problem and try to solve it in some other language you'll likely wind up reinventing some portion of Prolog in that language! If you look up solutions to the Zebra Puzzle written in other languages you'll see that most of them proceed by implementing some sort of logic solver that resembles a crude Prolog.) There may be practical real-world issues in performance or interfacing for a given application, but in general I'd say that good ol' Prolog is vastly underutilized. (Put another way, we're working harder than we should be.)
However, nowadays I'd start with Minizinc and its default solver gecode: http://www.minizinc.org/ For combinatorial puzzles it's even easier than Prolog and very efficient. Just read the short tutorial and you should be good to go solving the Zebra/Einstein problem or similar: http://www.minizinc.org/downloads/doc-latest/minizinc-tute.p... Minizinc is purely declarative. When more control is needed then you can use Prolog.
p = 711
q = 711000000
for a in range(1, 1 + p // 4):
if q % a == 0:
for b in range(a, 1 + (p - a) // 3):
if q % (a * b) == 0:
for c in range(b, 1 + (p - a - b) // 2):
d = p - a - b - c
if a * b * c * d == q:
print (a, b, c, d)
Does Prolog do the same pruning? Alternatively, it could be dumber (omit some of the pruning that my code does) or smarter (start by factoring 711000000 or something). xkcd_ugly(A, B, C, D) :-
P = 711,
Q = 711000000,
Max_A is 1 + P // 4,
between(1, Max_A, A),
Q mod A =:= 0,
Max_B is 1 + (P - A) // 3,
between(A, Max_B, B),
Q mod (A * B) =:= 0,
Max_C is 1 + (P - A - B) // 2,
between(B, Max_C, C),
D is P - A - B - C,
A * B * C * D =:= Q.
In SWI-Prolog, I get the following timings: ?- time(xkcd_ugly(A, B, C, D)).
% 383,992 inferences, 0.056 CPU in 0.056 seconds (100% CPU, 6825328 Lips)
A = 120,
B = 125,
C = 150,
D = 316 ;
% 3,274 inferences, 0.003 CPU in 0.003 seconds (100% CPU, 1229464 Lips)
false.
That is to say, it found the first solution in 0.056 seconds CPU time, then took an additional 0.003 seconds to prove that there are no further solutions. (This is the minimum of a handful of runs, there is quite a bit of variation.)Quick and very dirty benchmarks on the same machine run your Python code in about 0.02 seconds. The CLP(FD) code above takes about 0.1 seconds but it's a lot clearer.
[1] https://synthese.wordpress.com/2010/08/21/prologs-death/
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.
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_...
Enjoy.
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...
(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)
Q: How many Prolog programmers does it take to change a lightbulb?
A: noA 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.
At that point, I realized that if you prepare yourself in earnest for, say, the standardization process, or even to accomplish any concrete improvement in Prolog systems (such as better indexing, more advanced constraints, faster garbage collection etc.), then there is so much to do that there is barely enough time to do it properly!
Hence, I think it is fair to say we are are progressing as fast as we can, and such complex projects as building a full-fledged Prolog system inherently take an amount of time that we are not yet fully accustomed to. Prolog systems have been in development for many decades and are still being improved all the time. In my view, they are only now becoming truly interesting, with many great features such as multiple argument indexing, tabling and expressive constraints.
Pascal's issues regarding industrial use and poliferation of dialects were mostly fixed with ISO Extended Pascal, other than GNU, everyone else ignored it and focused on Turbo Pascal/Object Pascal compatibility instead.
Ruby and Eiffel happen to have ISO standards, but I bet even developers on those communities don't know it.
For a long time whatever ISO SQL was had not so much to do with what RDMS were actually providing.
ISO only matters if it is something vendors actually care about.
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);
}Also functional programming heavily encourages splitting up code into digestible chunks (they're called functions ;) )
Ps: I currently prefer my .NET as F# and so on but debuggability doesn’t feel biggest strength indeed altough it’s usually ok.
Also, Prolog code is often "split into digestible chunks". Even more than other languages, in fact, because it's rather hard to write nested loops or nested predicates or nested many other things.
If you were ever taught Prolog, it seems that you weren't taught well. You might want to risk a second look.
I find it very easy to write nested loops in Prolog:
findall(A
,findall(B
,findall(D
,findall(...)
,G)
,E)
,C)
To paraphrase the old saying, a good Python programmer can write Python in any language.Incidentally, my impression has been that the use of a declarative (or pure functional) language leads to spending drastically less (if any at all) time debugging. If your code makes sense (to you), it will work. Or, as an old adage goes, "If it compiles, it works."
First, many types of mistakes that are common when working with lower-level languages cannot occur at all when you use a declarative language. For example, with a logic programming language, you cannot accidentally double-free a pointer or write into unintended portions of memory.
Second, when working with a high-level language, the code is much shorter than if you had used a lower-level language. This makes it easier to debug, and also easier to get right already in the first few tries.
Third, once there is a mistake, it can be found in ways that fit the overall paradigm nicely. For example, in pure Prolog, if your predicate terminates and has a mistake, then it is either too specific or too general (or both), and you can debug both cases very systematically and even automatically, using built-in mechanisms of the language.
Declarative debugging methods for Prolog were pioneered by Ehud Shapiro in his 1982 PhD thesis, Algorithmic Program Debugging:
https://cpsc.yale.edu/sites/default/files/files/tr237.pdf
I also highly recommend Ulrich Neumerkel's teleteaching environment GUPU for systematically finding mistakes in Prolog programs:
This isn't said about the declarative nature of languages so much as it is about the benefits of powerful static type systems, in my experience.
It's quite easy to write Prolog programs that look right (to me, someone who doesn't know Prolog well) but that compile, successfully run to completion, and produce incorrect results (or don't terminate). In Haskell, the compiler actually rejects a huge amount of incorrect programs that I thought were going to work (and the fact that I thought that shows that the declarative nature of the code wasn't sufficient) and then once the typechecker is finally happy, the code often does actually work without further debugging (this is a common experience, and what the saying is referring to, I believe); in Prolog (or dynamically typed functional languages like Scheme), there's very little of that, and I'm left to catch most bugs on my own (even if like you said there won't be as many because they'd be so obvious in the first place).
Prolog might be exceedingly clear once you learn how to read it and it might eliminate errors that way, but "if it compiles, it works" is a terrible description of that. "If it looks right to someone who knows the language well, it works" is much closer, but not as punchy. The entire point of the original saying is that you don't need the experience with the language to get that, because the compiler itself will tell you if you're wrong when your types won't line up.
As far as the nearby statement that maybe I didn't learn dissection correctly, that may indeed be the case, but was also my original point: perhaps the real problem is that nobody knows how to TEACH functional/logical programming right, and that's why they have not caught on in the mainstream despite being around several decades. I'd love to "get" the benefits, but it just won't click. Sometimes you have to teach programmers how to think, not just what to think.
You may want to try working with network before making this statement, when you cannot step through a function because of timeouts. Or maybe even looking at tracing debuggers, like strace, ltrace, or Erlang's gdb, which all do little more than "printing things to the console".
Logging (and logging-like tools) is a very important way of debugging services, you know.
That's how you think and program in FP as well. Not just debugging, I mean: FP is all about divide and conquer. In fact, Wadler's seminal paper "Why Functional Programming Matters" [1] is all about what he calls modularity, i.e. splitting a problem in parts and then gluing it back together.
[1] https://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.p...
Eh... What? It's procedural code that can change anything anywhere and thus can not be easily separated into independent pieces.
Bottom line- yes, you can add print statements etc, but you can also directly debug your Prolog code just like you'd do for an imperative language.
Tiny Prologue-style "engines" can be fun and educational, but they are not a substitute for actual Prolog.
Question, is there any industrial strength Prolog for Commom Lisp, besides the Allegro product?
Then A.I. boom fizzled. Neither the first or last business cycle.
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
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.
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.
Here is more information:
https://cs.stackexchange.com/questions/60965/is-c-actually-t...
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!
Edit: I found Journal of Machine Learning Research 7 (2006) 307–342, Kernels on Prolog Proof Trees: Statistical Learning in the ILP Setting
process_create('/bin/cat',
[],
[stdout(pipe(Out)),stdin(pipe(In))]),
write(In, "hello"), nl(In), close(In),
read_line_to_codes(Out, Codes).A modern logic programming language: https://github.com/mcsoto/cosmos
Turbo Prolog is now known as Visual Prolog. Just for those who wondered what happened to it and might want to ude it.
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.
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
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 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).