Prolog is a nice language. I use it occasionally, from time to time.
But approaching it every subsequent time makes me feel less and less comfortable syntactically.
The modern programming languages are moving to allow
programmer less repeating himself
omit unnecessary pieces if they can be deduced, or their names are just placeholders.
The DCG is a step in the right direction allowing one to write
sentence --> noun_phrase, verb_phrase.
instead of
sentence(A,Z) :- noun_phrase(A,B), verb_phrase(B,Z).
but its entanglement with difference lists makes it less useful.
So what I am looking for are projects giving Prolog
a more compact syntactic representation, while preserving its semantic expressiveness.
Higher-order programming based on call/N is still a pretty much unexplored terrain. Major implementations like SICStus Prolog added call/N as late as 2006. So there is still a lot to explore. Consider library(lambda), library(reif) (both here) and other definitions using the meta-predicate declaration.
One thing you might want to look into in case of Swi-Prolog are actual language extensions introduced specifically by Swi-Prolog 7:
http://www.swi-prolog.org/pldoc/man?section=extensions
Another thing is Quasi-Quotation library which allows you to insert pieces of code in your own language (defined using DCG) inside "regular" Prolog code:
http://www.swi-prolog.org/pldoc/man?section=quasiquotations
The last thing I can recommend is the list of additional Swi-Prolog packages, some of which are specifically designed to extend the language, e.g. 'func', 'lambda', etc.:
http://www.swi-prolog.org/pack/list
Related
I'm reading several texts and online guides to understand the possibilities of prolog meta-interpreters.
The following seem like solid use cases:
proof explainers / tracers
changing proof search strategy, eg breadth first vs depth first
domain specific languages
Question - what other compelling use-cases are there?
Quoting from A Couple of Meta-interpreters in Prolog which is a part of the book "The Power of Prolog":
Further extensions
Other possible extensions are module systems, delayed goals, checking for various kinds of infinite loops, profiling, debugging, type systems, constraint solving etc. The overhead incurred by implementing these things using MIs can be compiled away using partial evaluation techniques. [...]
This quite extends your proposed uses, e.g., by
changing the search of p(X) :- p(s(X)). to detect loops (including "obvious" ones like this one),
hinting at where most compute time is spent ("profiling"),
or by reducing a program to a simpler fragment that is easier to analyse—but still has the property of interest: unexpected non-termination (explained via failure-slice), unexpected failure, or unexpected success.
In my opinion, define the DCGs (Definite Clause Grammars) as a compact way to describe the lists in Prolog, is a poorly way to define them. As far as I know, the DCGs are not only used in Prolog, but also in other programming languages, such as Mercury.
In addition, they are called DCGs, because they represent a grammar in a set of definite clauses (Horn clauses), the basis of logic programming.
So why if an entire Prolog program can be written using definite clauses, DCGs are solely defined as a compact way to describe the lists in Prolog?
Note: The doubt arises from the description for the tag dcg given by SO.
The extended info from the DCG tag wiki provides additional information, which I think is both correct and also in close agreement with your first point:
"DCGs are usually associated with Prolog, but similar languages such
as Mercury also include DCGs."
Regarding your second point: Emphasizing the close association with Prolog lists is in my opinion well justified, since a DCG indeed always describes a list, and typically also quite compactly.
I wish to be able to look up the existence of a term as fast as possible in my current prolog program, without the prolog engine traversing all the terms until it finally reaches the existing term.
I have not found any proof of it.. but I assume that given
animal(lion).
animal(zebra).
...
% thousands of other animals
...
animal(tiger).
The swi-prolog engine will have to go through thousands of animals trying to unify with tiger in order to confirm that animal(tiger) is in my prolog database.
In other languages I believe a HashSet would solve this problem, enabling a O(1) look up... However I cannot seem to find any hashsets or hashtables in the swi-prolog documentation.
Is there a swi-prolog library for hashsets, or can I somehow built it myself using term_hash\2?
Bonus info, I will most likely have to do the look up on some dynamically added data, either added to a hashset data-structure or using assertz
All serious Prolog systems perform this O(1) lookup via hashing automatically and implicitly for you, so you do not have to do it yourself.
It is called argument-indexing, and you find this explained in all good Prolog books. See also "JIT (just-in-time) indexing" in more recent versions of many Prolog systems, including SWI. Indexing is applied to dynamically added clauses too, and is one reason why assertz/1 is slowed down and therefore not a good choice for data that changes more often than it is read.
You can also easily test this yourself by creating databases with increasingly more facts and seeing that the lookup time remains roughly constant when argument indexing applies.
When the built-in first argument indexing is not enough (note that some Prolog systems also provide multi-argument indexing), depending on the system, you can construct your own indexing scheme using a built-in or library term hashing predicate. In the case of ECLiPSe, GNU Prolog, SICStus Prolog, SWI-Prolog, and YAP, look into the documentation of the term_hash/4 predicate.
I'm implementing a Prolog interpreter, and I'd like to include some built-in mathematical functions (sum, product, etc). For example, I would like to be able to make calculations using knowledge bases like this one:
NetForce(F) :- Mass(M), Acceleration(A), Product(M, A, F)
Mass(10) :- []
Acceration(12) :- []
So then I should be able to make queries like ?NetForce(X). My question is: what is the right way to build functionality like this into my interpreter?
In particular, the problem I'm encountering is that, in order to evaluate Sum, Product, etc., all their arguments have to be evaluated (i.e. bound to numerical constants) first. For example, while to code above should evaluate properly, the permuted rule:
NetForce(F) :- Product(M, A, F), Mass(M), Acceleration(A)
wouldn't, because M and A aren't bound when the Product term is processed. My current approach is to simply reorder the terms so that mathematical expressions appear last. This works in simple cases, but it seems hacky, and I would expect problems to arise in situations with multiple mathematical terms, or with recursion. Is there a better solution?
The functionality you are describing exists in existing systems as constraint extensions. There is CLP(Q) over the rationals, CLP(R) over the reals - actually floats, and last but not least CLP(FD) which is often extended to a CLP(Z). See for example
library(clpfd).
In any case, starting a Prolog implementation from scratch will be a non-trivial effort, you will have no time to investigate what you want to implement because you will be inundated by much lower level details. So you will have to use a more economical approach and clarify what you actually want to do.
You might study and implement constraint languages in existing systems. Or you might want to use a meta-interpreter based approach. Or maybe you want to implement a Prolog system from scratch. But don't expect that you succeed in all of it.
And to save you another effort: Reuse existing standard syntax. The syntax you use would require you to build an extra parser.
You could use coroutining to delay the evaluation of the product:
product(X, A, B) :- freeze(A, freeze(B, X is A*B))
freeze/2 delays the evaluation of its second argument until its first argument is ground. Used nested like this, it only evaluates X is A*B after both A and B are bound to actual terms.
(Disclaimer: I'm not an expert on advanced Prolog topics, there might be an even simpler way to do this - e.g. I think SICStus Prolog has "block declarations" which do pretty much the same thing in a more concise way and generalized over all declarations of the predicate.)
Your predicates would not be clause order independent, which is pretty important. You need to determine usage modes of your predicates - what will the usage mode of NetForce() be? If I were designing a predicate like Force, I would do something like
force(Mass,Acceleration,Force):- Force is Mass * Acceleration.
This has a usage mode of +,+,- meaning you give me Mass and Acceleration and I will give you the Force.
Otherwise, you are depending on the facts you have defined to unify your variables, and if you pass them to Product first they will continue to unify and unify and you will never stop.
I'm writing a Prolog interpreter as an exercise and wondering what I should be aiming for. Unfortunately there are many versions of Prolog to choose from and they are documented to various degrees. I quickly found this question from someone who was apparently expecting far too much from the internet by wanting a detailed html specification of Prolog. The answer to that was that you can get the ISO standard for $30, but that's rather impractical. Users are never going to pay $30 just to read about Prolog when they can get a Prolog interpreter for even less money, so if you pay the money and conform to the standard few people will ever recognize your effort. Therefore it doesn't surprise me at all that the ISO standard isn't universally respected.
Starting from the assumption that the ISO standard is a joke, what is the real version of Prolog that an interpreter should be aiming for? I don't mean that every little Prolog interpreter should fully implement every feature, but when constructing a Prolog interpreter there's no end to the little decisions that must be made. How should someone discover the consensus of the Prolog community about what Prolog should be?
If you are writing a Prolog system as an exercise, don't expect that you get too much done. After all, it is quite an effort.
To start with, aim for the core of the ISO standard, that is 13211-1:1995 including Cor.1:2007
and Cor.2:2012. That core is pretty much supported by many systems like: IF, SWI, YAP, B, GNU, SICStus, Jekejeke, Minerva. So while this core just covers the very basics, it will be still a lot of work to you.
Then, you can consider what further direction you want to go. From a standard's viewpoint these are implementation specific extensions. Systems pretty much differ in the way they offer extensions, so there is no clear way to choose. The most popular systems are SICStus (commercial) and SWI (open source). An open source system with better conformance than SWI is GNU.
You are putting a lot of quite debatable implications into your question, so let me try to sort some out:
Price of standards. ISO standards do cost something - these documents have a certain legal status - depending on your country and legislation. Freely available web documents can serve as evidence only. See for example the C standard which you get for the same prices: One official high price (USD 285) and a reduced one by INCITS (USD 30). The difference is only the cover sheet. At least, you can get the Prolog standard for a significantly reduced price.
Relevance. There is just one standard. And systems conform quite closely. Where they differ, they differ rather randomly. As an example, look at this detailed comparison of syntax which covers both reading and writing terms. Typically, such differences are reported by users who get hit by one or another difference. These differences are nowhere formally defined.
I don't agree with your assumption about ISO Prolog, indeed I would suggest to try to implement a small subset of ISO Prolog (i.e. be 'sure' to properly implement findall/setof).
A principal problem with ISO standard it's the module directive. Then choose an implementation to model modules, or skip them altogether.
Even some 'undiscussed' builtin will be difficult to implement, depending on the language you use (C, Haskell, Lisp, SQL, Javascript, C++...) and the choices you will do about the degree of translation. Most implementations out there are not interpreters, but bytecode compilers with various degrees of runtime support. The most used choice for the bytecode level is Warren's Abstract Machine (WAM, as you surely know).
When I wrote my Prolog interpreter, many years ago, I designed and implemented an object oriented database model, using algorithm ABC instead of the WAM, and I designed and implemented the Variables handling with ingenuity... but I left out setof/bagof, for instance...
I think SWI-Prolog pretty-much drives the Prolog standard nowdays, so take a look at their documentation... Other than that, what you are asking is being debated over and over again during the past years in the Prolog Standardization meetings. Some argue that tabling should be made into the standard, others claim the same for automatic indexing, and so on. So, in my humble opinion, the best you can do is "mimic" what SWI does for most stuff, and you'll be almost certainly in the standard