In the query below, firstly I'm getting X = H128, where does that come from? Also why is it returning yes? Is it because the variable X is actually not defined and we are testing for that condition?
?- not(X==3).
X = H128
yes
Your query is using an uninstantiated variable (X).
When checking whether X is instantiated with the term 3 it (X==3) it fails because X is uninstantiated.
Therefore, not(X==3) will succeed as the prolog engine cannot prove X==3.
Your prolog interpreter is thus returning 'yes' (due to the negation as failure approach of the interpreter), and X remains uninstantiated.
That is why the interpreter shows X = H128, where H128 is a dummy uninstantiated variable.
What was your original intention? It could be that you wanted to state that X is not equal to 3. For inequality many Prolog systems offer dif/2:
?- dif(X,3).
dif(X,3).
In this query we ask for values for X that are not equal to 3. So which values are not equal? Actually, quite a lot: Think of 1, 2, the term 3+3, c, the list [2,3,4] and many more. So giving a concrete answer like X = 4 would exclude many other valid answers. The answer here is however: The query holds for all X that are not equal to 3. The actual evaluation is therefore delayed to a later moment.
?- dif(X,3), X = 3.
false.
Here we got in a situation where X got the value 3 - which does not hold.
?- dif(X,3), X = 4.
X = 4.
And here a concrete valid value is accepted, and the restriciton dif(4,3) is removed.
Yes, it is because the variable X is not bound by the first goal, not(X==3). Actually the not/1 metapredicate can never produce a binding, even if it succeeds. That's because success of not means the inner goal fails. Note that not(X=3) would fail because X=3 can succeed when X is free (and can be bound to value 3).
Related
I came across following:
?- f(X) = X.
X = f(X).
?- f(a) = a.
false.
Why unification works for f(X) = X, but not for f(a) = a? Is it because first simply says name return value of f(X) as X, whereas second tries to check if return value of f(a) is a? But f() is undefined here!! Also, I guess, there is no such concept as "return value" in prolog. Then, whats going on here?
In your first example, X is a variable (identifier starts with capital letter, look it up). A free variable unifies with anything. (almost anything. you are creating a cyclic term, this will not work if you try to "unify with occurs check", look it up).
In your second example, a is an atom. It only unifies with a free variable or with itself. Since f(a) is not a the unification fails.
You are correct that there is no such thing as "return value". You might treat the success or failure of a goal as the "return value", but I don't know how much this helps.
Either way, there is no f() in Prolog. This is not a function. You don't need to define it. It is just a compound term (look it up). It is a data structure, in a way.
I would expect that the following should always be true if a comparison backtrack, right? unless it goes into an infinite loop!
?- Y=2 , random:random(1,3,X), X =\= Y.
Y = 2,
X = 1.
?- Y=2 , random:random(1,3,X), X =\= Y.
false.
but I got false!
In general, my question is why doesn't comparison backtrack?
Thanks for all the answers. My confusion seemed to come primarily from my expectation of random keep generating new-random numbers, so I confused that comparison was not backtracking, instead, the reason was that random does its thing only once and fails afterwards.
I was unaware of semi-determinate nature of some predicates.
But now I can be on a lookout ;) for cases like this. thanks again.
In your example, there is nothing to backtrack.
All predicates you are using in these examples ((=)/2, random/3 and (=\=)/2) are semi-deterministic: This means that they either fail, or succeed exactly once.
In other words, they can all succeed at most once.
Therefore, if at least one of these predicates fails, then the query fails.
To generate a succession of pseudo-random numbers on backtracking, use for example repeat/0.
Warning: random/3 is an impure predicate: It may yield different solutions even though the query is exactly the same. It may lead to failure on one invocation, and to success on another. This complicates testing and reasoning about your code considerably.
Prolog works with what are called Horn-clauses. This means that each term individually, for example Y=2, is a separate goal in a question to be answered. The result will be yes or no for each goal, and if all goals answer yes, the question is answered with yes.
What your code asks is as follows:
%Is Y equal to 2 or can it be made equal?
%Yes, Y is a variable and can be assigned the numerical atom 2
Y=2 ,
%Give me a random number between 1 and 3.
%Is X equal to the random number or can it be made equal?
%Yes, X is a variable and can be assigned the outcome atom of random:random
random:random(1,3,X),
%is the term contained within X NOT equivalent to Y?
X =\= Y.
You can check out existing comparison predicates in for example the SWI documentation or on Learn Prolog Now!.
Depending on your implementation you can use trace and write to output the actual atoms in the variables, allowing you to explore how your program actually works.
?- trace, (Y=2 , random:random(1,3,X), write(X),nl, X =\= Y). %SWI-Prolog
SWI-prolog online editor
Infinite recursion looks like p(P) :- p(P).. It has a call to the question it is supposed to solve inside the answer itself, meaning to solve for p(P) it will check p(P), which never ends.
Backtracking only happens when Prolog has choicepoints. Choicepoints are points where in the decision tree, there are MULTIPLE POSSIBLE WAYS to satisfy the question Prolog is currently processing. Prolog works from top to bottom, then left to right.
Think of a cars salesman who gets asked "which car is the best for me?". He has more than one possible car to sell you, so he'll start showing you different cars that meet your criteria. The car needs to have a transport capacity of a volume over 400 liters? All cars that don't satisfy this condition are not presented as a solution.
Prolog does a depth-first search, meaning it goes down to the first answer it finds, then checks whether there's other ways to answer it. If there is no result, the answer is no. If there is at least one solution, the answer is yes and you get all possible answers for your question. This way you only get results that satisfy a whole chain of goals you've set.
I think this will help.
% Generate random value from Min to Max(with backtrack)
rand_backtrack(Min,Max,RandVal):-
create_list(Min,Max,List),
randomize_list(List,Randomized),
length(Randomized,Len),
% Choose one Variable from Randomized (From first element to last).
% When backtrack occured, next element is chosen.
between(1,Len,Idx),
nth1(Idx,Randomized,RandVal).
% create integer order list
% [Min,Min+1,Min+2,....,Max]
create_list(Max,Max,[Max]):-!.
create_list(Min,Max,[Min|Rest]):-
Min1 is Min+1,
create_list(Min1,Max,Rest).
% shuffle List.
% result always changes.
% ex.randomize_list([1,2,3,4,5,6],R) R=[4,2,6,1,3,5]
%
randomize_list([Val],[Val]):-!.
randomize_list(List,[RandVal|RestRandomized]):-
length(List,Len),
random(1,Len,RandIdx),
nth1(RandIdx,List,RandVal),
select(RandVal, List, Rest),
!,
randomize_list(Rest,RestRandomized).
?- rand_backtrack(3,19,A).
A = 6 ;
A = 4 ;
A = 8 ;
A = 13 ;
A = 15 ;
A = 16 ;
A = 9 ;
A = 18 ;
A = 7 ;
A = 3 ;
A = 12 ;
A = 10 ;
A = 17 ;
A = 11 ;
A = 14 ;
A = 5 ;
A = 19.
I am writing a rule that is looking for a particular integer. I assumed I can write something like this
find_number(X):-
integer(X),
X > 1, X < 5.
Then expect the result of a query to integer(X) to result in X=2, X=3, X=4, false. Instead, I just get a false result. The only way I found to write this rule is to use numlist/3 like so
find_number(X):-
numlist(2, 4, NumList),
member(X, NumList).
Can anyone explain why this is?
Your reasoning would be perfectly valid iff integer/1 were an actual relation that satisfies basic logical properties.
For example, in classical logic, a unary predicate P satisfies the following property:
If P(σ(T)) is satisfiable for any substitution σ and term T, then P(T) is also satisfiable.
This seems completely obvious and of course holds also for all pure predicates in Prolog.
The problem is that integer/1 is not a pure relation.
In particular, we have for example:
?- integer(3).
true.
Yet the following more general query fails:
?- integer(X).
false.
Is there any integer? No.
Believe it or not, that's how integer/1 actually works.
Clearly, something seems not quite right for such predicates, and so there are better alternatives in all widely used modern Prolog systems. I strongly recommend you use such alternatives instead, to get the most out of Prolog.
For the case of integers, I recommend you check out CLP(FD) constraints (clpfd).
For example, in GNU Prolog, your code could look like this:
good_number(X) :-
X #> 1,
X #< 5.
With the following queries and answers:
| ?- good_number(X).
X = _#2(2..4)
| ?- good_number(X), fd_labeling([X]).
X = 2 ? ;
X = 3 ? ;
X = 4
This works exactly as we expect a relation to work! I have taken the liberty to change the name such that it makes sense also in more specific cases, where there is nothing left to "find":
| ?- good_number(3).
yes
Depending on your Prolog system, you may have to import a library to use such more declarative features. See also logical-purity for more information.
You get only false because integer/1 tests if the input is an integer and if it is it succeeds else if it is not an integer or if it is a variable that is not instantiated as in your case, then it fails.
You could use between/2 built in predicate:
find_number(X):-between(2,4,X).
This will return:
?- find_number(X).
X = 2 ;
X = 3 ;
X = 4.
While studying the language Prolog I found the following true or false question:
In Prolog ?- X is X+1 results in the increment of the variable X by one.
A teacher said it's false, however I don't understand why. Won't X be X+1 from now on? Why is it false?
Prolog does not work with variables like elements that can change value. A variable is an element that currently has no value, once it has a value, it cannot change that value (except for backtracking in which the unification is undone).
In case X already has a value, X+1 will be calculated, but you cannot unify 3 with 4:
?- X=3, X is X+1.
false.
In case X is ungrounded at that moment, the is predicate will fail:
?- X is X+1.
ERROR: is/2: Arguments are not sufficiently instantiated
The question probably wants to demonstrate one of the fundamental differences between imperative programming and logic programming: in imperative programming a variable can be assigned a (new) value, in logic programming a variable can only grounded once (except for backtracking). Once fully grounded, you cannot ground it a different way.
Playing with Prolog for the first time and while I thought I knew what it basically is good for, I find it hard to get anything done in it. So, I tried to find the easiest possible task and even fail to accomplish that.
I think it is due to me not knowing how prolog data types (numbers) are supposed to work or they have special syntax.
So, my first attempt to classify even numbers was:
even(0).
even(X) :- even(X-2).
Result: stack overflow for the query: even(2).
So I thought well if this is not it, then maybe it is:
even(0).
even(X+2) :- even(X).
Result of even(2): false.
So my simple question is: How to write such simple things in prolog? Is it all not working because i use numbers?
Why not do it the normal way:
is_even(X) :-
X /\ 0x1 =:= 0.
If you want to enumerate non-negative even numbers upon backtracking when the argument is not bound, this is a different thing altogether. It is probably easy to just say:
even(X) :-
between(0, infinite, X),
is_even(X).
You can use the second definition like this:
?- even(X).
X = 0 ;
X = 2 ;
X = 4 ;
X = 6 . % and so on
There are some differences between is_even/1 and even/1:
is_even/1 will work for any integer, positive or negative
is_even/1 will, surprisingly enough, work for expressions that evaluate to integers, too, for example, X = 3, ..., is_even(X + 1). This is because =:= accepts an arithmetic expression on either side.
even/1 uses between/3, so the domain of X and error conditions are the same as for the third argument of between/3.
As a consequence, even/1 does not work with negative integers or arithmetic expressions.
But wait, there's more!
Apparently, between(0, infinite, X) is not something you can do in almost any Prolog apart from SWI. So, instead, you can use another predicate that will enumerate positive integers (list lengths):
even_f(X) :-
length(_, X),
is_even(X).
(Thank you to #false for this)
Use is/2 to force the arithmetic evaluation. On their own, Prolog terms are just structural symbolic entities, X-2 is a compound term of arity 2, -(X,2):
3 ?- write_canonical( X-2 ).
-(_,2)
true.
But is is for arithmetic expressions:
4 ?- Z is 5-2.
Z = 3.
Your definition should thus be
even(X):- X=:=0 -> true
; X > 0 -> Y is X-2, even(Y).
The drawback of such definition is that it can't be called in a generative fashion, like even(X) to get all the evens generated one after the other.
It is only good for checking a given number. For simplicity, it ignores the negative numbers and always fails for them.