Prolog basic questions - prolog

First, what do you recommend as a book for learning prolog. Second, is there an easy way to load many .pl files at once? Currently just doing one at a time with ['name.pl'] but it is annoying to do over and over again. I am also using this to learn.
Thanks

First, welcome to Prolog! I think you'll find it rewarding and enjoyable.
The books I routinely see recommended are The Art of Prolog, Programming Prolog and Clause and Effect. I have Art and Programming and they're both fine books; Art is certainly more encyclopedic and Programming is more linear. I consult Art and Craft a lot lately, and some weirder ones (Logic Grammars for example). I'm hoping to buy Prolog Programming in Depth next. I don't think there are a lot of bad Prolog books out there one should try to avoid. I would probably save Craft and Practice for later though.
You can load multiple files at once by listing them:
:- [file1, file2, file3].
ALso, since 'name.pl' ends in '.pl' you can omit the quotes; single quotes are really only necessary if Prolog wouldn't take the enclosed to be an atom ordinarily.
Hope this helps and good luck on your journey. :)

If you are incline to a mathematical introduction, Logic, Programming and Prolog (2ED) is an interesting book, by Nilsson and Maluszinski.
Programming in Prolog, by Clocksin and Mellish, is the classic introductory textbook.

In SWI-Prolog, also check out:
?- make.
to automatically reload files that were modified since they were consulted.

You can check out this question. There are several nice books recommended back there.

This is a nice short little intro: http://www.soe.ucsc.edu/classes/cmps112/Spring03/languages/prolog/PrologIntro.pdf
I also want to say there's a nice swi oriented pdf out there, but I can't find it.

I won't repeat the classic choices already mentioned in other answers, but I will add a note about Prolog Programming in Depth by Michael Covington, Donald Nute, and Andrew Vellino. Two chapters I would like to highlight are the chapters on hand tracing and defeasible rules. The former shows you how to trace out a Prolog computation on pencil and paper in an efficient and helpful manner. The latter shows you how to create Prolog code that supports defeasible rules. Unlike the rules you are accustomed to in Prolog that either succeed or fail outright and are not affected by anything not stated in the rule itself, defeasible rules can succeed on the information stated in the rule yet can be undercut by other rules in the knowledge base making the expression that are generally true but have exceptions easier in a manner that is compact and easy to understand. Said better by the book "A defeasible rule, on the other hand, is a rule that cannot be applied to some cases even though those cases satisify its conditions, because some knowledge elsewhere in the knowledge base blocks it from applying."
It's an intriguing concept that I have not found in other books.

Related

how do I approach Prolog

I have taken up Prolog course in my university. The coursework requires us to write prolog programs. I am able to write simple programs, however I am finding it little hard to digest the complex programs. Any suggestions how to proceed or how do I study this subject ? what is the approach to tackle this kind of course. Any help appreciated.
Thanks.
I write an answer (which is probably just rant) because I struggle with the same problems. If a question gets closed I think the answer still stays?
what is the approach to tackle this kind of course.
Like all courses, you collect all material that your teacher/instructor/professor gives and find the books they recommend. You do the exercises as the way they expect. Do not be clever with your solutions, be clever with finding what your instructor wants to see! Try to find old exams and study them; esp. if you can find graded exams (if you are lucky and "resourceful"... ask older students for help!)
Any suggestions how to proceed or how do I study this subject ?
It is difficult to learn Prolog. I try to learn it at University and the teacher says one thing. Then I pick up a book ("Sterling and Shapiro") and it says another thing. Then I go online and I find yet another two very different things ("Amzi Amazing Adventure" and "Learn Prolog Now!"). There is also "Expert systems in Prolog" (from the Amzi website) and it is still another thing. I come to StackOverflow and I find yet other answers that are NOWHERE in all the texts I have tried to read.
The best place to learn for me is the SWI-Prolog predicate documentation: this is outrageous, don't you think? At least it is consistent....
And then many of the answers here on Stackoverflow I have tried to learn from are talking about things that make no sense (to me), probably because I don't know Prolog, but how to learn it? And almost all questions are homework, and almost all answers to homework are like little lectures that talk about ISO and logic and pureness but no clear answers.
In conclusion: "Sterling and Shapiro" was at least complete, and not too strange; and SWI-Prolog has good predicate documentation and even code examples.
EDIT: nowhere nowhere in all texts do you read about modules, but how do you write big programs without module system? Even the C++ book by Stroustrup explains how to use headers and source files to maintain a bigger program. Again, you go and read the chapter on modules in the SWI-Prolog documentation.
EDIT2: I study "Computer Science" so I maybe know "programming" and "data structures" and "algorithms" and I understand what is "proof tree" and "backtracking" and such things. Prolog is just another language. So why is it so difficult to teach it and learn it? This is an open question. I don't want to ask it on Stackoverflow because it will be closed.
EDIT3: Because you have tagged "clpfd", there is yet another text:
https://www.metalevel.at/prolog
It shows many solutions with clp(fd) that I did not see in any other of the texts I cited. It is useful and consistent but again it is different from all other texts. Maybe if I read and study everything I can find I can give you a real answer.
But do you want to pass the course or learn Prolog? Do you want a good grade and minimum effort? You need to find answers to such questions first!

Discussion about Abductive logic programming vs Answer Set Programming

I am looking to clarify the some things about abductive logic programming vs. Answer set programming.
I with some classmates are creating a game. In this game there are "heroes" (special npcs). The heroes have goals and behaviors.
(All of this is story driven)
What I would like the heroes to react to a player's or another hero's action then decide what to do from there.
A teacher told us about a paper called "RoleModel: Towards a Formal Model of Dramatic Roles for Story Generation" it explains abductive logic programming. Through my research I found Answer Set Programming.
Question:
Is there a difference between the ALP paradigm and the ASP paradigm?
Is one better then other for my purposes?
Is there another option?
You're really asking three questions. I'm not qualified to answer any of them, but I'm going to take a crack at it anyway.
Is there a difference between the ALP paradigm and the ASP paradigm?
Yes. ASP is a paradigm in which your search problem is made into a model that can be handed over to different solvers. The paper you reference says in section 4.1 that they follow the ASP paradigm and use deductive and abductive reasoning concurrently. So you can see that abductive and deductive are acting as tactical solvers inside a larger ASP process.
Based on what I read on Wikipedia, this is a good approach because abductive reasoning is about providing explanations rather than logical consequences. I could see how you would like that in story generation; "Mary hates Sue, therefore Mary killed Sue" is a deduction but "Mary hates Sue, because Sue ran over her dog" seems more like an abduction, based on my cursory reading. You would want both to flesh out a story, or it's going to get pretty dull.
Is one better then other for my purposes?
All you've said about your purposes is that you're making a game. I am not a game developer but I feel fairly confident is assuring you that nothing like this is used in a typical game. Game AI is its own whole field. I would be shocked if any of this stuff was used in a major game.
That said, RoleModel shows you can do it, and it uses both, with ASP controlling a combined ALP/DLP process. It seems likely to me that the two are pretty separable and since one can use the other, I would guess they are not in strict opposition to each other. If it worked for RoleModel game, the real question isn't can it be done, is it a good idea, but is it a good fit for what you're trying to accomplish? If you're trying to build an action-shooter, I would wager that other, simpler approaches will work out better; if you're trying to build a rich RPG, maybe it will be OK.
Is there another option?
Probably. I would investigate AI for games. The priorities are different enough that I would expect their literature starts in completely different places and goes in radically different directions, but I could be mistaken.
Any logic programming that supports hypothetical reasoning, can support ALP. Since ASP supports hypothetical reasoning, it can also support ALP. Hypothetical reasoning is a search where temporarily facts are assumed.
With standard ISO core Prolog we can simulate assuming a fact by the following code. The code leaves a choice point and doesn't work correctly if there is a cut involved, this is why specialized systems are nevertheless needed:
assumez(P) :- assertz(P).
assumez(P) :- retract(P), fail.
We can now solve the following abductive problem:
abducible :- (assumez(amount(glucose,low));assumez(amount(glucose,medium))),
(assumez(amount(lactose,medium));assumez(amount(lactose,hi))).
feed(lactose) :- amount(glucose,low), amount(lactose,hi).
feed(lactose) :- amount(glucose,medium), amount(lactose,medium).
A possible query runs as follows:
?- abducible, feed(lactose), listing(amount/2).
amount(glucose, low).
amount(lactose, hi).
Yes;
amount(glucose, medium).
amount(lactose, medium).
Yes ;
No
The above solution uses backward chaining. A forward chaining solution, and something that is closer to ASP choice operators, can be provided as well. The choice operator in ASP will do the hypothetical variants, we only use (;)/2 as a choice operator:
:- use_module(library(minimal/delta)).
:- multifile abducible/0.
:- dynamic abducible/0, amount/2, feed/1.
:- forward feed/2.
post(amount(glucose,low));post(aamount(glucose,medium)) <= posted(abducible).
post(amount(lactose,medium));post(amount(lactose,hi)) <= posted(abducible).
post(feed(lactose)) <= posted(amount(glucose,low)), posted(amount(lactose,hi)).
post(feed(lactose)) <= posted(amount(glucose,medium)), posted(amount(lactose,medium)).
A possible query runs as follows:
?- post(abducible), feed(lactose), listing(amount/2).
amount(glucose, low).
amount(lactose, hi).
Yes ;
amount(glucose, medium).
amount(lactose, medium).
Yes ;
No
FYI: As has been mentioned, some systems for performing inductive and abductive logic programming use ASP systems. A free open source example is XHAIL https://github.com/stefano-bragaglia/XHAIL
There is also a paper describing this version:
Bragaglia S., Ray O. (2015) Nonmonotonic Learning in Large Biological Networks. In: Davis J., Ramon J. (eds) Inductive Logic Programming. Lecture Notes in Computer Science, vol 9046. Springer, Cham
It could be argued that Sherlock Holmes is actually famous for abductive reasoning not deductive reasoning... so I think there is some interesting scope for a detective game using ALP. :).

How does Prolog technically work? What's under the hood?

I want to learn more about the internals of Prolog and understand how this works.
I know how to use it. But not how it works internally. What are the names of the algorithms and concepts used in Prolog?
Probably it builds some kind of tree structure or directed object graph, and then upon queries it traveres that graph with a sophisticated algorithm. A Depth First Search maybe. There might be some source code around but it would be great to read about it from a high level perspective first.
I'm really new to AI and understanding Prolog seems to be a great way to start, imho. My idea is to try to rebuild something similar and skipping the parser part completely. I need to know the directions in which I have to do my research efforts.
What are the names of the algorithms and concepts used in Prolog?
Logic programming
Depth-first, backtracking search
Unification
See Sterling & Shapiro, The Art of Prolog (MIT Press) for the theory behind Prolog.
Probably it builds some kind of tree structure or directed object graph, and then upon queries it traveres that graph with a sophisticated algorithm. A Depth First Search maybe.
It doesn't build the graph explicitly, that wouldn't even be possible with infinite search spaces. Check out the first chapters of Russell & Norvig for the concept of state-space search. Yes, it does depth-first search with backtracking, but no, that isn't very sophisticated. It's just very convenient and programming alternative search strategies isn't terribly hard in Prolog.
understanding Prolog seems to be a great way to start, imho.
Depends on what you want to do, but knowing Prolog certainly doesn't hurt. It's a very different way of looking at programming. Knowing Prolog helped me understand functional programming very quickly.
My idea is to try to rebuild something similar and skipping the parser part completely
You mean skipping the Prolog syntax? If you happen to be familiar with Scheme or Lisp, then check out section 4.4 of Abelson & Sussman where they explain how to implement a logic programming variant of Scheme, in Scheme.
AI is a wide field, Prolog only touches symbolic AI. As for Prolog, the inner workings are too complex to explain here, but googling will give you plenty of resources. E.g. http://www.amzi.com/articles/prolog_under_the_hood.htm .
Check also Wikipedia articles to learn about the other areas of AI.
You might also want to read about the Warren Abstract Machine
typically, prolog code is translated to WAM instructions and then executed more efficiently.
I would add:
Programming Languages: An interpreter based approach by Samuel N. Kamin. The book is out of print, but you may find it in a University Library. It contains a Prolog implementation in Pascal.
Tim Budd's "The Kamin Interpreters in C++" (in postscript)
The book by Sterling and Shapiro, mentioned by larsmans, actually contains an execution model of Prolog. It's quite nice and explains clearly "how Prolog works". And it's an excellent book!
There are also other sources you could try. Most notably, some Lisp books build pedagogically-oriented Prolog interpreters:
On Lisp by paul Graham (in Common Lisp, using -- and perhaps abusing -- macros)
Paradigms of Artificial Intelligence Programming by Peter Norvig (in Common Lisp)
Structure and Interpretation of Computer Programs by Abelson and Sussman (in Scheme).
Of these, the last one is the clearest (in my humble opinion). However, you'd need to learn some Lisp (either Common Lisp or Scheme) to understand those.
The ISO core standard for Prolog also contains an execution model. The execution model is of interest since it gives a good model of control constructs such as cut !/0, if-then-else (->)/2, catch/3 and throw/1. It also explains how to conformantly deal with naked variables.
The presentation in the ISO core standard is not that bad. Each control construct is described in a form of a prose use case with a reference to an abstract Prolog machine consisting of a stack, etc.. Then there are pictures that show the stack before and after execution of the control construct.
The cheapest source is ANSI:
http://webstore.ansi.org/RecordDetail.aspx?sku=INCITS%2FISO%2FIEC+13211-1-1995+%28R2007%29
In addition to the many good answers already posted, I add some historical facts on Prolog.
Wikipedia on Prolog: Prolog was created around 1972 by Alain Colmerauer with Philippe Roussel, based on Robert Kowalski's procedural interpretation of Horn clauses.
Alain was a French computer scientist and professor at Aix-Marseille University from 1970 to 1995. Retired in 2006, he remained active until he died in 2017. He was named Chevalier de la Legion d’Honneur by the French government in 1986.
The inner works of Prolog can best be explained by its inventor in this article Prolog in 10 figures. It was published in Communications of the ACM, vol. 28, num. 12, December. 1985.
Prolog uses a subset of first order predicate logic, called Horn logic. The algorithm used to derive answers is called SLD resolution.

What is more interesting or powerful: Curry, Mercury or Lambda-Prolog?

I would like to ask you about what formal system could be more interesting to implement from scratch/reverse engineer.
I've looked through some existing and open-source projects of logical/declarative programming systems. I've decided to make up something similar in my free time, or at least to catch the general idea of implementation.
It would be great if some of these systems would provide most of the expressive power and conciseness of modern academic investigations in logic and its relation with computational models.
What would you recommend to study at least at the conceptual level? For example, Lambda-Prolog is interesting particularly because it allows for higher order relations, but AFAIK is based on intuitionist logic and therefore lack the excluded-middle principle; that's generally a disadvantage for me.
I would also welcome any suggestions about modern logical programming systems which are less popular but more expressive/powerful.
Prolog was the first language which changed my point of view at programming. But later I found it to be not so high-level as I'd like to see it.
Curry - I've tried only Munster CC, and found it somewhat inconvenient. Actually, at this point, I decided to stop ignoring Haskell.
Mercury has many things which I wanted to see in Prolog. I have a really good expectation about the possibility to distinguish modes of rules. Programs written in Mercury should inspire compiler to do a lot of optimizations (I guess).
Twelf.
It generalizes lambda-prolog significantly, and it's a logical framework and a metalogical framework as well as a logic programming language. If you need a language with a heavy focus on logic as well as computation, it's the best I know of.
If I were to try to extend a logic based system, I'd choose Prolog Cafe as it is small, open sourced, standards compliant, and can be easily integrated into java based systems.
For the final project in a programming languages course I took, we had to embed a Prolog evaluator in Scheme using continuations and macros. The end result was that you could freely mix Scheme and Prolog code, and even pass arbitrary predicates written in Scheme to the Prolog engine.
It was a very instructive exercise. The first 12 lines of code (and and or) literally took about 6 hours to write and get correct. It was pretty much the search logic, written very concisely using continuations. The rest followed a bit more easily. Then once I added the unification algorithm, it all just worked.

Becoming operational in Prolog quickly

My company has a project running in Prolog and I want to clarify few things about how to go about learning it. I know Prolog is different. It should not be learnt just like any other language.
Having said that, and considering the fact that I did not lay my hands on any Prolog book yet, Is there any book or online resource, where I can learn Prolog the way how we learn C/C++? What I mean is , just to be operational in C/C++, you just need to know the structure of the program, like main { } , loops, conditions, branches, and few functions that you can use to start writing basic programs in C/C++.
Just this way can I learn Prolog and is there any book that just gives me an idea how to Program in Prolog? (basics, loops, how to implement conditions, program structure, what's predicate? how to use it? how to define it? and so on...).
If you're after a single book, I can highly recommend "The Art of Prolog":
Coming to Prolog from something like C/C++ isn't just a matter of learning a programming language. It's a wholly different way of thinking about programming.
Prolog is about asking the computer questions (or 'queries' if you like). Computation is almost a side-effect of the computer trying to answer your question. There is no meaningful equivalent to loops or conditionals because a prolog programmer wouldn't think in those terms.
A good Prolog program looks like a description of the problem that you're trying to solve decomposed into recursive cases and subproblems rather than lists of instructions organised into functions or classes.
The best way to learn Prolog is to set aside all your previous programming experience. Actually thinking about C and C++ will make Prolog harder to learn and use. Try to adopt a beginner's mind and maybe an approach more like an algebraist than a programmer.
As a supplement to the Prolog tutorials and textbooks mentioned in the other answers, I would suggest having a quick look at this short document:
Prolog for Imperative Programmers
I think it's part of what you're looking for. It won't teach you Prolog, but it will help bridge the gap to understanding Prolog. It describes the basics of Prolog using terminology that experienced non-Prolog programmers would understand. For example, it shows you control structures in Prolog, i.e. sequence, selection and repetition. It does assume that you've already started learning Prolog, though.
It's good if you want to understand something new in terms of something you already know. However, armed with this knowledge/understanding, there is a risk that you could end up writing C code in Prolog syntax. Good luck!
What's wrong with Learn Prolog Now, which is usually the top recommendation each time this kind of question gets asked?
It may not give you exactly the terminology you want -- I believe it doesn't even mention "predicate" (uses "Facts, Rules, and Queries" instead) or "loops" (it just shows how to use recursion instead) -- but getting the terminology right once the concepts are clear should be simple, fast, and easy, and "Learn Prolog Now" does seem to do a good job about making the concepts clear.

Resources