
Introduction to logic programming with Prolog - matchilling
https://www.matchilling.com/introduction-to-logic-programming-with-prolog/
======
barry0079
When writing a Prolog program a while ago I stumbled across an old mailing
list where someone posted the following joke. Q. "How many Prolog Programmers
does it take to change a lightbulb?" A. No.

~~~
ninjamayo
Can't resist, I will add
[https://en.wikipedia.org/wiki/Answer_set_programming](https://en.wikipedia.org/wiki/Answer_set_programming)
programming on this.

Q. How many Answerset programmers does it take to change a lightbulb? A. {1},
{1,2}, {1,2,3}, {2,1}, {2,1,3}, {2,3,1}

~~~
sp332
... {3,1}, {1,3}

------
zmonx
I agree with what Sylvain Soliman said about this on Reddit: It's a nice
tutorial for the 80's parts of the language:

[https://www.reddit.com/r/programming/comments/7hp2xw/introdu...](https://www.reddit.com/r/programming/comments/7hp2xw/introduction_to_logic_programming_with_prolog/dqspj4p/)

In modern Prolog systems, you would use more declarative features such as
_constraints_ to model combinatorial tasks like map coloring.

Make sure to check out modern Prolog features if you are interested in
learning the language seriously!

~~~
agumonkey
are modern prolog just a layer on top of the old semantics or somehow an
incompatible paradigm ?

~~~
giardini
The OP is likely speaking of "Constraint Logic Programming(CLP)".

The set of CLP languages is generally implemented as a superset or add-on
package(s) to a Prolog implementation. For example, SICStus Prolog and SWI-
Prolog have CLP modules, e.g.:

[https://sicstus.sics.se/sicstus/docs/3.7.1/html/sicstus_32.h...](https://sicstus.sics.se/sicstus/docs/3.7.1/html/sicstus_32.html)

[http://www.swi-prolog.org/pldoc/man?section=clp](http://www.swi-
prolog.org/pldoc/man?section=clp)

and "Constraint Handling Rules(CHR):

[http://www.swi-prolog.org/pldoc/man?section=chr](http://www.swi-
prolog.org/pldoc/man?section=chr)

To the best of my knowledge the modules are written in Prolog. A look at those
links will give you an idea of how CLP is used. There are modules available
for CLP(X) where X is one of:

B = boolean,

Z = integers,

Q = rational numbers,

R = real(floating point) numbers,

FD = finite domains (see "CLP(FD) Constraint Logic Programming over Finite
Domains"
[http://www.pathwayslms.com/swipltuts/clpfd/clpfd.html](http://www.pathwayslms.com/swipltuts/clpfd/clpfd.html)
)

etc.

One can understand how constraining the domain of interest (reducing the
search space) to say, the integers, might make search more efficient.

~~~
zmonx
In a sense, yes, these modules are written in Prolog. However, that is not the
full story: CLP requires special interface predicates that the underlying
Prolog system must provide. You cannot implement CLP "on top" of just any
Prolog system with reasonable performance and correctness.

Devising and implementing such suitable interface predicates is quite hard,
and only a very small number of Prolog systems have succeeded with this so
far.

For example, the SWI interface for CLP is too limited in practice, and its
constraint solvers have elementary mistakes also because of the limitations of
the interface predicates it provides.

In contrast, SICStus Prolog provides a much more general interface to
attributed variables that supports all widely used constraint solvers (finite
domains, Boolean variables, rational numbers etc.) with good performance and
no known mistakes.

The tutorial you link to has several rather severe shortcomings, and I cannot
recommend it for learning CLP(FD). Please see my profile page if you are
interested in Prolog resources.

------
virgilp
I find the section 5.3 from the paper "Out of the tar pit"[1] describes it
very well:

> It is for this reason that Prolog falls short of the ideals of logic
> programming. Specifically it is necessary to be concerned with the
> operational interpretation of the program whilst writing the axioms.

I haven't heard of any approach that generalizes the goals of logic
programming in a far better way. Is there any? (on specific usecases, having a
sort of rule engine for running your "business rules" can indeed be an
excellent approach)

[1] [https://github.com/papers-we-love/papers-we-
love/blob/master...](https://github.com/papers-we-love/papers-we-
love/blob/master/design/out-of-the-tar-pit.pdf)

~~~
mathetic
Ah, that's a problem with many facets.

It is not that we can't come up with a logic language that is more
declarative, it is just that telling the program everything about the universe
is so damn dull. For example, ordering of your body predicates will often be
based on what you think intuitively their sizes of solutions are going to be
e.g. `plus(A,B,C), solution(C,X).` You know that plus is injective, so you put
it first but from a logical perspective putting solution predicate first is
just as sensible. If the language allowed you to express relative sizes of the
predicates, then this could have been done automatically, but it would involve
coding the order of predicates somewhere else in the program!

You also need to get rid of cuts in Prolog, if you want to be closer to true
declarative programming. You might like to then try Datalog (alas, not Turing
complete).

Another approach is to separate concerns more clearly. The part of Prolog that
encodes and solves a logical problem is often different than the one dealing
with IO for example. Ideally, you want to be more declarative in the former
domain and more imperative in the latter. This can (and probably have been
done) with a monadic approach.

~~~
Hendrikto
I do not get why you mean by plus being injective.

`plus(1, 2, C). C = 3.`

`plus(0, 3, C). C = 3.`

Isn't that a counterexample, showing how it is not injective?

~~~
mathetic
Yes, I was thinking total with respect to _intuitive_ arguments, but wrote
injective. Sorry.

------
pjmlp
For those looking to gentle introduction to logic programming, Tarski's World
was a very good book.

[https://ggweb.gradegrinder.net/tarskisworld](https://ggweb.gradegrinder.net/tarskisworld)

[https://web.stanford.edu/group/cslipublications/cslipublicat...](https://web.stanford.edu/group/cslipublications/cslipublications/site/1575864843.shtml)

Might help, instead of jumping straight into Prolog.

~~~
agumonkey
oh you reminded me of a program we used in college named the same. It was
about model theory and valid logic clauses (blurry memories)..

~~~
telekid
Yep, showed up in a First Order Logic course for me. IIRC, it was bundled with
a book?

Edit - this one:
[https://web.stanford.edu/group/cslipublications/cslipublicat...](https://web.stanford.edu/group/cslipublications/cslipublications/site/1575864843.shtml)

------
pgtan
I try to introduce my boy (12) in programming trough Scratch but still no big
success. However, we solved recently two math homework exercises with Prolog
(logic) and MetaPost (geometry) which caused some effect, so I'm thinking to
deepen in that languages or may be switch to Logo as intermediate lisp like
solution.

~~~
flavio81
That is the best way to introduce computers to a kid: "let it do the hard work
for you".

Logo used to be very popular for kids here in the '80s. I learnt Logo when i
was 7, then i "progressed" over the years to Basic, C, Pascal, C++, Java, C#,
Python and now, after about 28 years, Lisp. And now I realize Logo is close to
Lisp in many ways and a far more powerful language than some of the ones I
"progressed" to.

~~~
kbp
It's always been interesting to me how Logo, a Lisp dialect, was so successful
as a language for teaching children to program, but so many people still go
around with the idea that Lisp is really hard to wrap your head around.

~~~
kazinator
> _People still go around with the idea that Lisp is really hard to wrap your
> head around._

Usually, the people who genuinely had a "hard to wrap head around experience"
weren't actually using Lisp but a different language called Scheme which is
hard to do for anything practical, if you stick just to the standard-defined
dialect.

Chances are that when they used Scheme, it was a school setting, and they were
complete or almost complete programming newbies, and were asked to do
everything with recursion, and also given demanding homework, like
interpreting Scheme in Scheme and whatnot.

------
legionth
I hated it in university and hate it until this very moment. I get what this
language is doing and why it is great for special usecases. But I can
absolutly can not read code written in Prolog. Staring at 3 lines of code and
not knowing what the hell it does, gives me nightmares till today.

You can write a quicksort in a few lines. You can traverse over a tree very
easily. But understanding these few lines takes me more time than writing it
in C, Java, PHP etc.. But I guess it is all training...

~~~
pjmlp
I love Prolog, to the point of having taken part in the Portuguese university
national logic championship back in the 90's.

On our degree, we had three logic programming classes, starting from logic
programming as pure math all the way to deep Prolog exercises.

~~~
flavio81
I didn't know there were Logic championships using Prolog!

P.S: Vocé é Portuguese, lisper e _tambén_ fá de Prolog? You impress me more
each day, pjmlp!

~~~
pjmlp
Obrigado, but actually it is due to quality of many of the teachers I had the
opportunity to interact with during the 90's version of FCT/UNL. :)

------
vanderZwan
I've seen a few contalks about logic programming, read a few articles, and
aside from the intellectual curiosity in itself I can see that it is very
elegant in certain circumstances (although I lack the hands-on experience to
feel what those circumstances are).

Since doing a whole program in prolog isn't really practical for me, is there
any way to use the logic programming _paradigm_ in mainstream programming
languages to deal with specific problems that fit it?

~~~
tannhaeuser
The point of Prolog as a practical logic programming language really is that
it is portable accross Prolog implementations based on ISO Prolog (and maybe
prolog-commons API compatibility). If you're using a Prologish tool (a Java
framework, say) that is not quite Prolog, then you're loosing the
compatibility for very little gain IMHO.

Applications domains I've used Prolog for: discrete planning, game logic,
limited/rule-based NLP such as postal address checking, combinatorial test
case generation, decision problems in formal language theory used for eg.
deciding properties of business processes, other small problems in software
engineering such as code generation from domain models with roundtripping, or
O/R mapping.

~~~
vanderZwan
> The point of Prolog as a practical logic programming language really is that
> it is portable accross Prolog implementations based on ISO Prolog (and maybe
> prolog-commons API compatibility). If you're using a Prologish tool (a Java
> framework, say) that is not quite Prolog, then you're loosing the
> compatibility for very little gain IMHO.

I feel like I might be missing something obvious, but I'm not getting what the
"compatibility" you refer to would give me in my specific situations? It looks
like you're saying _" if you write a Prolog program, it's compatible across
Prolog platforms."_ Well, sure, but how is that fundamentally more portable
situation than (for example) _" if I have a logic programming framework in
ES16, it works in all browsers that run modern JavaScript"_?

If I'm specifically trying to do something in the browser (again, for example)
and have a problem within that context where logic programming might be
useful, having a way to use logic programming in JS makes more sense, doesn't
it?

~~~
tannhaeuser
I'm not disagreeing that if you're developing a Web app, embedding logical or
constraint programming techniques into a JavaScript API could make sense.
OTOH, there's an obvious way for data exchange between JavaScript and Prolog,
in that JSON can be be parsed by using Prolog's embedded `op/2` predicate and
operator-precedence parser for defining custom DSLs.

~~~
jononor
What would be the workflow in Prolog if I want to import a set of facts from
an external source, like a database/JSON/CSV?

~~~
tannhaeuser
JSON could be parsed as a term by Prolog, with suitable priority/associativity
definitions for the comma, colon, and curly brace operators.

For CSV, you could write a DCG grammar for the particular file format at hand.

Integration with a relational DB, itself being based on logic, would be very
different. Most Prologs have APIs to map tables to predicates.

------
jwi
FYI, there's an updated version of the 99 Prolog problems by its original
author here: [https://sites.google.com/site/prologsite/prolog-
problems](https://sites.google.com/site/prologsite/prolog-problems)

~~~
matchilling
Thanks for the hint, I've updated the URL to point to the new version.

------
heneryville
I don't know if this is just coincidence, but this blog post is fantastically
similar to another [1] on Prolog, down the the same quotes, and the same
example, though different code.

[1] [https://bernardopires.com/2013/10/try-logic-programming-a-
ge...](https://bernardopires.com/2013/10/try-logic-programming-a-gentle-
introduction-to-prolog/)

------
1001101
Another excellent resource for learning Prolog is the book "The Art of
Prolog." One of the finest language texts you will ever read.

~~~
sizeofchar
I read it recently and I can't recommend it enough. Even if you aren't really
interested in Prolog, it is a must read.

------
cmpb
Aja Hammerly[0] have a talk[1] at RubyConf this year titled “4 Programming
Paradigms in 45 Minutes”, and she used Prolog as her declarative language. She
implements a simple cash register in OO (Ruby), Functional (Racket),
Declarative (Prolog) and Procedural (Assembly). The Prolog one turned out to
be the shortest. It was really interesting!

[0] [https://github.com/thagomizer](https://github.com/thagomizer) [1]
[https://confreaks.tv/videos/rubyconf2017-4-programming-
parad...](https://confreaks.tv/videos/rubyconf2017-4-programming-paradigms-
in-45-minutes)

------
dmitriid
> Prolog has a straightforward syntax. You will pick up the few rules very
> quickly. Let us transform the Socrates example from earlier into an actual
> Prolog program and analyse what is happing inside the compiler.

Yeah, and no. This skips over the fact that this will not work in swipl, and
you need to write those rules in a separate file, and compile/load them.

This is mentioned way after the entire introduction, after the reader has
already given up on trying anything with prolog

------
sgt101
Is anyone reading this aware of any work on logic programming __in the large
__as in efforts that are harnessing the fact that answerset programming avoids
committed choice and so enables us to write reliable tractable programs, but
aims to make that possible in teams or in distributed settings?

~~~
ninjamayo
I haven't encountered anything across answer set programming in the large as
you put it. It is still pretty academic and mainly used for solving puzzle and
optimization problems.

~~~
sgt101
And yet declaring all business logic was once the way that all decisions would
be encoded!

~~~
ninjamayo
Looking at this from a more general perspective of the Symbolic AI approach I
would say it had its days. Data driven systems are proving to be a lot more
powerful and easy to build. I remember I used to spend ages trying to encode
my problems in AnswerSet or AgentSpeak and come up with all the rules. It
never worked!

------
chkte
I know how to code in Prolog. How can I take profit of it, apart from my
academic (undergraduate) interests?

Can I build something in particular, can I look for specific jobs?

~~~
gota
There are not that many companies using prolog code, but specialized AI
companies still do. I've worked as a consultant programmer developing large
decision-support systems for engineering projects and the bulk of the domain
logic was written in prolog. Most operational stuff was in C++ or Python,
still, so even in that project there were as many jobs for Python programmers
as there were prolog programmers

You don't truly appreciate the declarative paradigm until you are able to
describe (and find the best among) all billions of complex possibilities of
configurations of nuts and bolts following all these engineering laws,
practices and rules of thumb... in a hundred lines or less

I love Python and I'll introduce myself as a Python programmer, but part of me
will always have a deep respect for prolog and how utterly awesome it is in
the right context

------
maxxxxx
How does Prolog relate to ML systems? It seems they work in a similar way.
Input some learning data and then the system produces output based on these.

~~~
lou1306
Eh, they are quite different under the hood. To put it real simple (and
probably quite sloppy): Prolog determines the output by applying logic. ML
uses mathematics to analyze the input and "guesses" the output, based on the
training set.

As a corollary: Prolog will negate anything that can't be proven true from the
rules you give it. A ML algorithm will always give you some answer, though the
quality depends on the learning data.

~~~
gregdeveloper
I think he meant ML as the family of meta programming languages?

He did say systems though so you are probably right

~~~
lou1306
Also, the part about "Input some learning data" makes me think to Machine
Learning rather than Meta Language.

Btw, Prolog and ML might look like distant cousins: e.g. you use recursion and
pattern matching in both. But under the hood there are big differences that
arise from Prolog's logic programming paradigm: for instance, you can use
append(L1, L2, L3) both to concatenate _and_ split a list, depending on the
variables you set:

    
    
      append([1,2], [3,4], X)       % ==> X=[1,2,3,4]
      append([1,2], Y, [1,2,3,4])   % ==> Y=[3,4]

------
guruparan18
Back in 2006, I studied Prolong in my college as a pre-up course for A.I. From
my experience then, Prolog was easy for programming small tasks. I ended up
building a card game with some intelligence as a final project. Even then, I
spent most of the time designing cards to show up in console than time on
actual coding for game play/intelligence.

It could be fun to retry Prolog now.

------
ptrkrlsrd
Great tutorial! Made me want to go back to Prolog again. A little sidenote for
those who run MacOS with brew - you can install Prolog with "brew install swi-
prolog" instead of using the binary version.

------
jldupont
prolog interpreter in javascript, no server side code:
[http://prolog.jldupont.com/](http://prolog.jldupont.com/)

------
pulsarpietro
That Uni course is rubbish

