Prolog- Not the expected Output - prolog

I have this fact that returns the descendants but it only returns if "ascendente" is father/mother of "descendente". What am I doing wrong?
%descendenteDir(homem,mulher,filho)
descendenteDir('Tywin','Joanna','Ser Jaime').
descendenteDir('Tywin','Joanna','Cersei').
descendenteDir('Robert','Cersei','Joffrey').
descendenteDir('Robert','Cersei','Myrcella').
descendenteDir('Robert','Cersei','Tommen').
descendenteDir('Kevan','Dorna','Lancel').
descendente(Ascendente,Descendente):- descendenteDir(Ascendente,_,Descendente)
;descendenteDir(_,Ascendente,Descendente)
;descendenteDir(descendente(Ascendente,_),_,Descendente)
; descendenteDir(_,descendente(Ascendente,_),Descendente).

The descendente(Ascendente,_) part in the final rule is not quite right. It should be something like this:
descendente(Ascendente,Descendente):- descendenteDir(Ascendente,_,Descendente)
;descendenteDir(_,Ascendente,Descendente)
;descendenteDir(X,_,Descendente), descendente(Ascendente,X)
;descendenteDir(_,X,Descendente), descendente(Ascendente,X).
It's not the same as calling functions and getting returned values in languages like C++/Python/Java. In Prolog, you have a set of facts (the descendenteDir rules at the top), and some inference rules (the descendente rule). In the definition where you would use the rule recursively, you would have to provide a variable which would be bound to the values available (from the facts). That variable would later be used to infer the subsequent rules. Here X is that variable. Prolog will bind different values to it and try to infer the next part from the following clause.

Related

What do these mean in prolog?

First when I read up on different predicates on Prolog, like for example http_server, it's written like this: http_server(:Goal, +Options) what does : and + mean here? Sometimes ? is also written.
Secondly sometimes I see variables declared with an underscore before them like _Request, even though there isn't any another Request, why is that?
The +, -, : etc. sigils are called mode declarations. They describe the expected instantiation of predicate arguments, i.e., whether you are expected to call the predicate with an unbound variable, an instantiated term, etc. These are not completely standardized; here is a description of the conventions for SWI-Prolog: http://www.swi-prolog.org/pldoc/man?section=modes
As a first approximation, a + argument is an input to the predicate, you are supposed to provide a ground term. A - argument is an output of the predicate, the predicate will try to unify it with a term. A ? term may be partially instantiated at the call, and the predicate may instantiate it further. A : argument is a meta-argument, i.e., it is a goal to be called by the predicate (as in setof/3, for example).
In the example of http_server(:Goal, +Options), you are supposed to call this predicate with the first argument bound to a goal, probably a predicate name. The second argument must be instantiated, presumably to a list whose format is further described in the documentation. If you do not call this predicate like this, for example, if you pass an unbound variable as the second argument, you might get unexpected behavior or an instantiation error.
As for your second question (which would better have been separate), a variable that begins with an underscore is called an anonymous variable. Every such variable may only occur once per clause, except _ itself, which may occur several times and refers to separate variables at each occurrence.
Prolog systems usually emit a "singleton variable" warning for non-anonymous variables that occur only once, because those might be typos or a sign the programmer forgot something. You use anonymous variables to express the notion that "there must be something here (e.g., a predicate argument), but I don't care what it is". In your example, presumably you call a predicate that has a "request" argument, but in your particular use case you don't care about the request.

Prolog: Rules with nothing but anonymous variables in the head, and no body

Prolog's grammar uses a <head> :- <body> format for rules as such:
tree(G) :- acyclic(G) , connected(G).
, denoting status of G as a tree depends on status as acyclic and connected.
This grammar can be extended in an implicit fashion to facts. Following the same example:
connected(graphA) suggests connected(graphA):-true.
In this sense, one might loosely define Prolog facts as Prolog rules that are always true.
My question: Is in any context a bodiless rule (one that is presumed to be true under all conditions) ever appropriate? Syntactically such a rule would look as follows.
graph(X). (suggesting graph(X):-true.)
Before answering, to rephrase your question:
In Prolog, would you ever write a rule with nothing but anonymous variables in the head, and no body?
The terminology is kind of important here. Facts are simply rules that have only a head and no body (which is why your question is a bit confusing). Anonymous variables are variables that you explicitly tell the compiler to ignore in the context of a predicate clause (a predicate clause is the syntactical scope of a variable). If you did try to give this predicate clause to the Prolog compiler:
foo(Bar).
you will get a "singleton variable" warning. Instead, you can write
foo(_).
and this tells the compiler that this argument is ignored on purpose, and no variable binding should be attempted with it.
Operationally, what happens when Prolog tries to prove a rule?
First, unification of all arguments in the head of the rule, which might lead to new variable bindings;
Then, it tries to prove the body of the rule using all existing variable bindings.
As you can see, the second step makes this a recursively defined algorithm: proving the body of a rule means proving each rule in it.
To come to your question: what is the operational meaning of this:
foo(_).
There is a predicate foo/1, and it is true for any argument, because there are no variable bindings to be done in the head, and always, because no subgoals need to be proven.
I have seen at least one use of such a rule: look at the very bottom of this section of the SWI-Prolog manual. The small code example goes like this:
term_expansion(my_class(_), Clauses) :-
findall(my_class(C),
string_code(_, "~!##$", C),
Clauses).
my_class(_).
You should read the linked documentation to see the motivation for doing this. The purpose of the code itself is to add at compile time a table of facts to the Prolog database. This is done by term expansion, a mechanism for code transformations, usually used through term_expansion/2. You need the definition of my_class/1 so that term_expansion/2 can pick it up, transform it, and replace it with the expanded code. I strongly suggest you take the snipped above, put it in a file, consult it and use listing/1 to see what is the effect. I get:
?- listing(my_class).
my_class(126).
my_class(33).
my_class(64).
my_class(35).
my_class(36).
true.
NB: In this example, you could replace the two occurrences of my_class(_) with anything. You could have just as well written:
term_expansion(foobar, Clauses) :-
findall(my_class(C),
string_code(_, "~!##$", C),
Clauses).
foobar.
The end result is identical, because the operational meaning is identical. However, using my_class(_) is self-documenting, and makes the intention of the code more obvious, at least to an experienced Prolog developer as the author of SWI-Prolog ;).
A fact is just a bodiless rule, as you call it. And yes, there are plenty of use cases for bodiless facts:
representing static data
base cases for recursion
instead of some curly brace language pseudo code
boolean is_three(integer x) {
if (x == 3) { return true; }
else { return false; }
}
we can simply write
is_three(3).
This is often how the base case of a recursive definition is expressed.
To highlight what I was initially looking for, I'll include the following short answer for those who might find themselves asking my initial question in the future.
An example of a bodiless rule is, as #Anniepoo suggested, a base case for a recursive definition. Look to the example of a predicate, member(X,L) for illustration:
member(X,[X|T]). /* recursive base case*/
member(X,[H|T]):- member(X,T).
Here, the first entry of the member rule represents a terminating base case-- the item of interest X matching to the head of the remaining list.
I suggest visiting #Boris's answer (accepted) for a more complete treatment.

Status variable in Prolog

I need to code a process in which the program should run some rules base on a "Status variable", then I need to be able to change this Status variable in order to continue with the process. But I do not know if there is something like a "Status variable", any idea of how can I achieve it?
Your "status variable" could be a fact, which gets asserted (or retracted) to reflect the desired signal, although I don't think you can make such changes concurrent with a proof executing.
I think it would be cleaner to assert whatever state you need when the original process "gets stuck", and instead issue a new query when the status changes which could then use that state.
A declarative alternative to using a dynamic variable, as Scott suggested in his answer, is to use a stream variable. The idea would be to create and initialize a new stream variable, pass it (as a logic variable) to your rules, and update it with a new value when require. The rules would access (or update) at any time the current value of the stream variable. An example, using Logtalk implementation of stream variables, should make it clear (you can use Logtalk as a library with most Prolog compilers, including SWI-Prolog):
?- {library(streamvars)}.
% [ /Users/pmoura/logtalk/library/streamvars.lgt loaded ]
% (0 warnings)
true.
?- streamvars::new(SV, 1).
SV = [_G9, v(1)|_G13].
Notice that the stream variable, SV is represented by a list with a unbound tail, which allows us to add new values to it. The streamvars object provides predicates for creating a new stream variable, accessing its current value, and updating its value. A simple usage would be:
?- streamvars::new(SV, 1), streamvars::'=>'(SV, V1), streamvars::'<='(SV, 2), streamvars::'=>'(SV, V2).
SV = [v(_G31), v(1), v(2)|_G34],
V1 = 1,
V2 = 2.
The =>/2 and <=/2 predicates have corresponding operator definitions for some syntactic sugar, although those are not used above. Your rules would use these access and update predicates as necessary, with the stream variable being passed (threaded) from rule to rule.
The full documentation of the streamvars can be consulted at:
http://logtalk.org/library/streamvars_0.html
The source code can in turn be consulted at:
https://github.com/LogtalkDotOrg/logtalk3/blob/master/library/streamvars.lgt
The code is simple and you can easily adapted it to your application. A possible downside of using this implementation of stream variables is that, as shown above, all past elements are kept. If that's a problem in your case, then you will need to resort to non-declarative solutions such as using a dynamic predicate or mutables (i.e. global variables), which are provided in some Prolog systems.

Prolog: what is the - prefix in predicates / variables?

Example:
conditions([-on(a, b)]).
I have searched tirelessly but fruitlessly for the meaning of this and the + prefix. You are my last hope.
No context is provided, so I'm supposing this might come from something in documentation.
If you read the introductory material in the Prolog manual (SWI, Gnu, or whichever) they describe teh conventions. The +, -, and ? are used as a convention in documentation to indicate whether an variable is an input or an output or a variable (either). For example, from the Gnu Prolog manual:
+: the argument must be instantiated.
-: the argument must be a variable (will be instantiated if the built-in predicate succeeds).
?: the argument can be instantiated or a variable.
So, for example, atom_length/2 is described as;
atom_length(+atom, ?integer)
Which means you must provide atom (it can't be a variable) and integer can either be a variable (in which case atom_length will provide a value) or it can be instantiated (in which case atom_length will indicate whether your query is true or false)`.
You don't normally use the - or + in your code in this sense, unless you really intend to have it there as part of your term. Considering the given example, it looks like it may have been an intended part of the term:
conditions([-on(a, b)]).
The list parameter consists of a term, when spelled out fully, is -(on(a,b)) (-/1 with parameter that's on/2). The - here doesn't provide any function, it just adds structure (the structure being a term with name - and parameter on(a,b)).

Variables and how they are set and used in prolog

http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/2_1.html
So on that tutorial where it has:
conflict(Coloring) :-
adjacent(X,Y),
color(X,Color,Coloring),
color(Y,Color,Coloring).
Am I understanding this correctly, that Color is a variable and is set to a value after the first call to color and then that value is used in the second call to color?
Variables in Prolog:
All variables and arguments are local in scope to the predicate in which they are declared (aka first used). Excepting of course that variables may be passed as arguments (essentially "by reference") to another predicate.
Prolog variables are only "variable" until bound (unified) with something else. At that point they cease to be variable and become one with that with which they were unified. Hence the use of the term "unification": to unify is to become one.
Backtracking, of course, undoes any unification that might have occurred, returning things to the status quo ante as it were.
The special variable _ is the "anonymous variable". Each use, even within the same clause of a predicate is independent. For instance, given the facts
letter(a).
letter(b).
letter(c).
digit(1).
digit(2).
digit(3).
the predicate:
foo :- letter(A),number(A).
fails, whilst
foo :- letter(_),number(_).
will succeed (9 times, with backtracking).
Color it's a variable, but we can't say if it will get a value (in Prolog this is called binding) from the first or the second call to color/3. All depends on the color/3 definition. But given this code it's probable that your assumption it's ok.

Resources