Prolog greater_than /2 succ - prolog

I'm new to Prolog and I'm trying to resolve this exercise:
Define a predicate greater_than/2 that takes two numerals in the notation that we introduced in this lecture (i.e. 0, succ(0), succ(succ(0))...) as arguments and decides whether the first one is greater than the second one. E.g:
?- greater_than( succ(succ(succ(0))), succ(0) ).
yes.
?- greater_than( succ(succ(0)), succ(succ(succ(0))) ).
no.
This is my answer so far:
greater_than(X, 0).
greater_than( succ(succ(X)), succ(Y) ).
but of course doesn't work properly, so I'm asking anyone for help.
Thanks.

As you are looking for a recursive solution, you have to provide a base case and a recursive step.
The base case you provided is almost right. However it fails because it will succeed for example when both numbers are zero. It should succeed only when the left side is of the form succ(_) and the right side is zero.
The recursive step should take an element from each side and apply recursion.
Therefore this should work:
greater_than(succ(_), 0).
greater_than(succ(X), succ(Y)):-
greater_than(X, Y).

Related

Why does my list reversal only work correctly in one direction?

I have produced the following code.
list_reverse([],[]).
list_reverse([X],[X]).
list_reverse(Ls,[R|Rs]) :-
last_elem(Ls,R),
without_last_elem(Ls,Next),
list_reverse(Next,Rs).
last_elem([E],E).
last_elem([_|Xs],E) :-
last_elem(Xs,E).
without_last_elem([X,_|[]],[X|[]]).
without_last_elem([X|T0],[X|T1]) :-
without_last_elem(T0,T1).
Swipl:
?- list_reverse([1,2,3],X).
X = [3, 2, 1] ;
false.
This is exactly what I want.
However if I go in the opposite direction I get success, followed by non-termination.
?- list_reverse(X,[1,2,3]).
X = [3, 2, 1] ;
C-c C-cAction (h for help) ? a
abort
% Execution Aborted
What I am struggling to understand is why I first get a correct solution for X. Is my program correct or not?
I am not worried about reversing a list as much as I am about this pattern of getting a correct solution followed by non-termination. It is a pattern I have already come across a few times.
I am [worried] about this pattern of getting a correct solution followed by non-termination.
This is due to the very specific notion of (universal) termination in Prolog. In other programming languages termination is a much simpler beast (still an undecidable beast nevertheless). If, say, a function returns then it terminates (for that case). But in Prolog, producing an answer is not the end as there might be further solutions or just an unproductive loop. In fact, it's best not to consider your query ?- list_reverse(X,[1,2,3]). but rather the following instead.
?- list_reverse(X,[1,2,3]), false.
In this manner all distracting answers are turned off. The only purpose of this query is now either to show termination or non-termination.
After that,
you can either try to follow Prolog's precise execution path but that is as insightful as staring into a car's gearbox when you are lost (the gears caused you to move into the place where you are lost thus they are somehow the cause...). Or, you take a step back, and consider related program fragments (called slices) that share certain properties with your original program. For termination, a failure-slice helps you to better understand what is at stake. In your case consider:
list_reverse([],[]) :- false.
list_reverse([X],[X]) :- false.
list_reverse(Ls,[R|Rs]) :-
last_elem(Ls,R), false,
without_last_elem(Ls,Next),
list_reverse(Next,Rs).
last_elem([E],E) :- false.
last_elem([_|Xs],E) :-
last_elem(Xs,E), false.
?- list_reverse(X,[1,2,3]), false.
Since this failure slice does not terminate, also your original program doesn't terminate! And, it is much easier to reason here in this smaller fragment. If you want to fix the problem, you need to modify something in the visible part. Otherwise you will keep being stuck in a loop.
Note that none of the facts is part of the loop. Thus they are irrelevant for non-termination.
Also note that in list_reverse/2 the variable Rs is never used in the visible part. Thus Rs has no influence on termination! Please note that this is a proof of that property already. Does this mean that the second argument of list_reverse/2 has no influence on termination? What do you think?
The last_elem/2 can keep constructing larger lists, that all should be rejected. But you thus get stuck in an infinite loop.
We can make a function that works with accumulator, and iterates over both the two lists concurrently. That means that once the left or right list is exhausted, no more recursive calls will be made:
reverse(L1, L2) :-
reverse(L1, [], L2, L2).
reverse([], L, L, []).
reverse([H|T], L1, R, [_|T2]) :-
reverse(T, [H|L1], R, T2).
Here the [H|T] and [_|T2] pattern thus both pop the first item of the list, and we only match if both lists are exhausted.

Sums of the elements in list

I have to say that there is a similar quetion Sum of elements in list in Prolog needs little explanation, but still makes me confused.
Here is the following solution which needs some explanation.
sum([H],H).
sum([H|T],R):-sum(T,P),R is H + P.
Lets say we do sum([1,2,3],R).
sum([1,2,3],R)
sum([2,3],<unknown-1>)
sum([3],<unknown-2>)
so where it will fulfill the fact sum([H],H) ?
I do write the variable in sum([H],H), the only output for this case is 3,
which means that in the unknown-2 here is 3, why?
Just a beginner in prolog and any answers will be great appreciate.
The short answer: unification.
When, within the scope of a predicate clause, a variable name occurs more than once, all occurrences will be unified with each other. The predicate for unification is =/2, and is declared as operator, so =(A, A) and A = A mean the same. More importantly, this:
=(Term, Term).
is the definition of =/2 (see the documentation!)
In your example, you have a clause that says:
sum([H], H).
This means:
When the first argument of sum/2 is a list with exactly one element, the second argument of sum/2 is that element.
Because term unification is such a fundamental operation in Prolog, usually, it is not spelled out explicitly, as for example:
When the first argument of sum/2 is a list with exactly one element, that element and the second argument of sum/2 are unified with each other.
At least in the SWI-Prolog documentation, if unification is involved, it is usually described with "X is Y" instead of "X and Y are unified". See, for example, the documentation of min_member/2:
min_member(Min, List).
True when Min is the smallest member in the standard order of terms. Fails if List is empty.
It doesn't explicitly tell you that unification is used, and from that, the following behavior follows:
?- min_member(3, [1,2,X]).
X = 3.
I once asked a question about this because I found it too confusing.
By the way, with your current definition of sum/2, you can also get surprises because of the way that unification works. Look:
?- sum([1.5, 2.5], Sum).
Sum = 4.0 ; % unnecessary choice point but at least correct
false.
?- sum([1.5, 2.5], 4).
false. % Oops!
The SWI-Prolog library implementation suffers from the same problem:
?- sum_list([1.5, 2.5], Sum).
Sum = 4.0. % no choice point, at least
?- sum_list([1.5, 2.5], 4).
false. % Oops!
The work-around is to leave the second argument a free variable at first, and then use =:=/2, which does arithmetic comparison of numbers:
?- sum_list([1.5, 2.5], Sum), Sum =:= 4.
Sum = 4.0.
You can do this with your definition of sum/2 as well.
sumList([],0).
sumList([X|Tail],Sum):-
sumList(Tail,Sum1),
Sum is Sum1+X.

Prolog and limitations of backtracking

This is probably the most trivial implementation of a function that returns the length of a list in Prolog
count([], 0).
count([_|B], T) :- count(B, U), T is U + 1.
one thing about Prolog that I still cannot wrap my head around is the flexibility of using variables as parameters.
So for example I can run count([a, b, c], 3). and get true. I can also run count([a, b], X). and get an answer X = 2.. Oddly (at least for me) is that I can also run count(X, 3). and get at least one result, which looks something like X = [_G4337877, _G4337880, _G4337883] ; before the interpreter disappears into an infinite loop. I can even run something truly "flexible" like count(X, A). and get X = [], A = 0 ; X = [_G4369400], A = 1., which is obviously incomplete but somehow really nice.
Therefore my multifaceted question. Can I somehow explain to Prolog not to look beyond first result when executing count(X, 3).? Can I somehow make Prolog generate any number of solutions for count(X, A).? Is there a limitation of what kind of solutions I can generate? What is it about this specific predicate, that prevents me from generating all solutions for all possible kinds of queries?
This is probably the most trivial implementation
Depends from viewpoint: consider
count(L,C) :- length(L,C).
Shorter and functional. And this one also works for your use case.
edit
library CLP(FD) allows for
:- use_module(library(clpfd)).
count([], 0).
count([_|B], T) :- U #>= 0, T #= U + 1, count(B, U).
?- count(X,3).
X = [_G2327, _G2498, _G2669] ;
false.
(further) answering to comments
It was clearly sarcasm
No, sorry for giving this impression. It was an attempt to give you a synthetic answer to your question. Every details of the implementation of length/2 - indeed much longer than your code - have been carefully weighted to give us a general and efficient building block.
There must be some general concept
I would call (full) Prolog such general concept. From the very start, Prolog requires us to solve computational tasks describing relations among predicate arguments. Once we have described our relations, we can query our 'knowledge database', and Prolog attempts to enumerate all answers, in a specific order.
High level concepts like unification and depth first search (backtracking) are keys in this model.
Now, I think you're looking for second order constructs like var/1, that allow us to reason about our predicates. Such constructs cannot be written in (pure) Prolog, and a growing school of thinking requires to avoid them, because are rather difficult to use. So I posted an alternative using CLP(FD), that effectively shields us in some situation. In this question specific context, it actually give us a simple and elegant solution.
I am not trying to re-implement length
Well, I'm aware of this, but since count/2 aliases length/2, why not study the reference model ? ( see source on SWI-Prolog site )
The answer you get for the query count(X,3) is actually not odd at all. You are asking which lists have a length of 3. And you get a list with 3 elements. The infinite loop appears because the variables B and U in the first goal of your recursive rule are unbound. You don't have anything before that goal that could fail. So it is always possible to follow the recursion. In the version of CapelliC you have 2 goals in the second rule before the recursion that fail if the second argument is smaller than 1. Maybe it becomes clearer if you consider this slightly altered version:
:- use_module(library(clpfd)).
count([], 0).
count([_|B], T) :-
T #> 0,
U #= T - 1,
count(B, U).
Your query
?- count(X,3).
will not match the first rule but the second one and continue recursively until the second argument is 0. At that point the first rule will match and yield the result:
X = [_A,_B,_C] ?
The head of the second rule will also match but its first goal will fail because T=0:
X = [_A,_B,_C] ? ;
no
In your above version however Prolog will try the recursive goal of the second rule because of the unbound variables B and U and hence loop infinitely.

Prolog: redundant program points in failure-slice?

We are implementing diagnostic tools for explaining unexpected universal non-termination in pure, monotonic Prolog programs—based on the concept of the failure-slice.
As introduced in
the paper "Localizing and explaining reasons for nonterminating logic programs with failure slices", goals false/0 are added at a number of program points in an effort to reduce the program fragment sizes of explanation candidates (while still preserving non-termination).
So far, so good... So here comes my question1:
Why are there N+1 program points in a clause having N goals?
Or, more precisely:
How come that N points do not suffice? Do we ever need the (N+1)-th program point?
Couldn't we move that false to each use of the predicate of concern instead?
Also, we know that the program fragment is only used for queries like ?- G, false.
Footnote 1: We assume each fact foo(bar,baz). is regarded as a rule foo(bar,baz) :- true..
Why are there N+1 program points in a clause having N goals? How come that N points do not suffice?
In many examples, not all points are actually useful. The point after the head in a predicate with a single clause is such an example. But the program points are here to be used in any program.
Let's try out some examples.
N = 0
A fact is a clause with zero goals. Now even a fact may or may not contribute to non-termination. As in:
?- p.
p :-
q(1).
p.
q(1).
q(2).
We do need a program point for each fact of q/1, even if it has no goal at all, since the minimal failure slice is:
?- p, false.
p :-
q(1),
p, false.
q(1).
q(2) :- false.
N = 1
p :-
q,
p.
p :-
p.
q :-
s.
s.
s :-
s.
So here the question is: Do we need two program points in q/0? Well yes, there are different independent failure slices. Sometimes with false in the beginning, and sometimes at the end.
What is a bit confusing is that the first program point (that is the one in the query) is always true, and the last is always false. So one could remove them, but I think it is clearer to leave them, as a false at the end is what you have to enter into Prolog anyway. See the example in the Appendix. There, P0 = 1, P8 = 0 is hard coded.

prolog using recursion to find successor

I'm trying to learn prolog now and I started recursion topic. Came across this example for successor.
numeral(0).
numeral(succ(X)) :- numeral(X)
I do understand how it works in theory. It takes the number X and succ increments it. My questions here is, is succ an in-built predicate? Or is there something else going on in this example. Example taken from learnprolognow.org
Then I came across this exercise
pterm(null).
pterm(f0(X)) :- pterm(X).
pterm(f1(X)) :- pterm(X).
It is meant to represent binary, that is 0 is f0(null), 1 is f1(null), 2(10) is f0(f1(null)), 3(11) is f1(f1(null)) etc.
The question asks to define predicate (P1, P2) so that P2 is the successor of P1 by using pterms.
Could someone explain this question in more detail for me?
The way I see it now, I have to traverse back through P1 until I hit the end and then compare it to P2, but I'm not exactly sure about the syntax.
Any hints would be useful
succ is a compound term, not a built-in predicate.
Taking the two clauses in order you have:
numeral(0).
This means numeral(0) is true, i.e. 0 is a numeral
numeral(succ(X)) :- numeral(X)
This means numeral(succ(X)) is true if you can show that numeral(X) is true.
If you ask the query:
?- numeral(succ(succ(0)).
Then prolog will say True: numeral(succ(succ(0)) is true if numeral(succ(0)) is true. And numeral(succ(0)) is true if numeral(0) is true. And we know numeral(0) is true.
If you ask
?- numeral(X).
Then prolog will reply X=0 then X=succ(0) then X=succ(succ(0)) and so on as it finds terms which satisfy your clauses.
Now to answer your pterm question...
First think about the structure you are building. Its a binary number and the outermost term is the least significant bit. Here are some examples for things which are true:
1: succ(f1(null),f0(f1(null))
2: succ(f0(f1(null)),f1(f1(null))
3: succ(f1(f1(null)),f0(f0(f1(null)))
If you look at the examples for 2 and 3 above then you should be able to derive three cases of interest. As a hint the first case is that if the term is of the form f0(X) then the successor is f1(X).
seems that inspecting the top level argument could be enough. Just an hint
psucc(pterm(f0(X)), pterm(f1(f0(X)))).
...

Resources