Deeper Explanation of Prolog Count - prolog

Currently playing around in Prolog... I'm having trouble groking the count list rule. I haven't been able to find a good explanation anywhere. Can someone give me a break down of it at each recursion?
count(0, []).
count(Count, [Head|Tail]) :-
count(TailCount, Tail),
Count is TailCount + 1.
One place says that it is recursive (which makes sense to me) and another that says it isn't.

The procedure it's recursive, but not tail recursive. Writing tail recursive procedures is an optimization that allows the system to transform recursion into iteration, avoiding useless stack usage for deterministics computations (like the one we are speaking of).
In this case (that BTW it's the same of the builtin length/2, just with arguments swapped), we can use an accumulator, and rewrite the procedure in this way:
count(C, L) :- count(0, C, L).
count(Total, Total, []).
count(SoFar, Count, [_Head|Tail]) :-
Count1 is SoFar + 1,
count(Count1, Count, Tail).
Some system older required a cut before the recursive call, to make the optimization effective:
...,
!, count(Count1, Count, Tail).

The definition of the inference rule is recursive.
This program tries to count the quantity of elements inside the list.
count(0, []). This is an axiom, a fact, something that its true because you said so. Here you are stating that every empty list has a count of zero.
count(Count, [Head|Tail]) :-
count(TailCount, Tail),
Count is TailCount + 1.
This is an inference rule, that it a rule that dictates that the left part of :- is true if the right part is true. This inference rule also uses pattern matching, wicth matchs non empty lists ([Head|Tail]).
Specifically, the count rule says that the Count variable of a non empty list is the count of the Tail part of the list, plus 1 (the plus 1 is for counting the Head element of the list).

Related

How to find the last item in the third list, which is collected from the first and second list?

intersection([],L1,L2,L3).
intersection([H|T],L2,L3,[H|L4]):-member(H,L2),intersection(T,L3,L3,L4).
member(H,[H|T]).
member(X,[H|T]):-member(X,T).
This code makes the third list from the first and second list.
last([U],U).
last([_|L3],U) :- last(L3,U).
This piece of code looks for the last item in the list.
My problem is that I can’t figure out how to make these two pieces of code fit into one. That is, the program should find duplicate elements in the first and second list and display them in the third, and from the third list, display the last element multiplied by 3.
The main problem is intersection/4. I assume you wanted to write a deterministic predicate intersection/3 the first two arguments of which are fully instantiated at call time and the last argument of which is an output argument. By deterministic, I mean that intersection/3 should succeed exactly once without leftover choice points. The SWI-Prolog documentation contains a useful overview of determinism and mode declarations (although it does not enforce them).
It is useful to begin by writing a declarative specification of the predicate following the inductive definition of lists:
The intersection of [] and Ys is [].
The intersection of [A|Xs] and Ys is A prepended to the intersection of Xs and Ys if A is a member of Ys.
The intersection of [A|Xs] and Ys is the intersection of Xs and Ys if A is not a member of Ys.
The simplest translation of this specification into standard Prolog is:
intersection([],_,[]).
intersection([A|Xs],Ys,[A|Zs]) :-
member(A,Ys),
intersection(Xs,Ys,Zs).
intersection([A|Xs],Ys,Zs) :-
\+ member(A,Ys),
intersection(Xs,Zs).
If the first call to member/2 succeeds the second should fail. In order to avoid backtracking, unifying the current goal with the head of the second clause, and performing a redundant call to member/2, we place a cut after the occurrence of member/2 in the second clause.
intersection([],_,[]).
intersection([A|Xs],Ys,[A|Zs]) :-
member(A,Ys),
!,
intersection(Xs,Ys,Zs).
intersection([_|Xs],Ys,Zs) :-
intersection(Xs,Ys).
If the current goal unifies with the head of the first clause, it will not unify with the heads of later clauses. In order to prevent spurious backtracking, we place a cut in the (empty) body of the first clause. Whether this cut is necessary depends on your choice of Prolog implementation.
intersection([],_,[]) :-
!.
intersection([A|Xs],Ys,[A|Zs]) :-
member(A,Ys),
!,
intersection(Xs,Ys,Zs).
intersection([_|Xs],Ys,Zs) :-
intersection(Xs,Ys).
We are only interested in checking membership in the second list. Thus, we can replace the occurrence of member/2 with the semideterministic predicate memberchk/2. Here, semideterministic means that memberchk/2 succeeds or fails exactly once without leftover choice points.
intersection([],_,[]).
!.
intersection([A|Xs],Ys,[A|Zs]) :-
memberchk(A,Ys),
!,
intersection(Xs,Ys,Zs).
intersection([_|Xs],Ys,Zs) :-
intersection(Xs,Ys).
This implementation of intersection/3 is nearly identical to the implementation found in the SWI-Prolog library lists.pl. You can combine this predicate with an implementation of last/2 in order to complete your program. For example:
last_duplicate_tripled(Xs,Ys,N) :-
intersection(Xs,Ys,Zs),
last(Zs,M),
N is M * 3.
From here, I recommend doing the following:
Implement intersection/3 using metalogical predicates like findall/3.
Read #false's answer to this question.
Read #repeat's answer to this question.
They are doing something much more interesting and sophisticated than I attempted in this answer.

Why does these rules work? (finding last element in list in prolog)

I am trying to understand the following set of rules, which supposed to find the last element in a list (for instance my_list(X,[1,2,3]) gives X=3).
my_last(X,[X]).
my_last(X, [_|L]) :- my_last(X, L).
I understand the first fact - X is the last element of a list if X is the only element in it, but how does the second rule work? this looks a bit strange to me as a prolog noob, I'd love to know if there's an intutive way to interprate it.
T
Read the Prolog predicate as logical rules. If there is more than one predicate clause for the predicate, you can think of it as "OR":
my_last(X,[X]).
X is the last element of the list, [X].
my_last(X, [_|L]) :- my_last(X, L).
X is the last element of the list [_|L] if X is the last element of the list L.
The second clause is a recursive definition. So it does, ultimately, need to terminate with the recursive call not matching the head of the recursive clause that is calling it. In this case, L eventually becomes [] and will no longer match [_|L]. This is important because, otherwise, you will get an infinite recursion.

Merging two ordered lists ProLog

Hey so this is my code so far. I am only a begginer in prolog but i need it for school
firstElement([_|_], [Elem1|List1], [Elem2|List2]):-
Elem1 =< Elem2, merge([Elem1] , List1, [Elem2|List2]);
merge([], [Elem2], List2).
merge([Head|Tail], [Elem1|List1], [Elem2|List2]):-
Elem1 =< Elem2,!, add(Elem1,[Head|Tail],[Head|Tail1]),
merge([Head|Tail1], List1, [Elem2|List2]);
add(Elem2,[Head|Tail],[Head|Tail1]),
merge([Head|Tail1], [Elem1|List1], List2).
merge([Head|Tail], [], [Elem2|List2]):-
add(Elem2,[Head|Tail],[Head|Tail1]).
merge([Head|Tail], [Elem1|List1], []):-
add(Elem1,[Head|Tail],[Head|Tail1]).
merge([Head|Tail], [], []).
add(X,[],[X]).
add(X,[Y|Tail],[Y|Tail1]):-
add(X,Tail,Tail1).
I found out that everytime it gets out of a merge it keeps forgetting the last number so it gets back to nothing in the end.
I think you’ve gotten very mixed up here with your code. A complete solution can be had without helpers and with only a few clauses.
First let us discuss the two base cases involving empty lists:
merge(X, [], X).
merge([], X, X).
You don’t quite have these, but I see some sort of recognition that you need to handle empty lists specially in your second and third clauses, but I think you got confused and overcomplicated them. There’s really three scenarios covered by these two clauses. The case where both lists are empty is a freebie covered by both of them, but since that case would work out to merge([], [], []), it’s covered. The big idea here is that if you exhaust either list, because they were sorted, what you have left in the other list is your result. Think about it.
This leaves the interesting case, which is one where we have some items in both lists. Essentially what you want to do is select the smaller of the two, and then recur on the entire other list and the remainder of the one you selected the smaller value from. This is one clause for that:
merge([L|Ls], [R|Rs], [L|Merged]) :-
L #< R,
merge(Ls, [R|Rs], Merged).
Here’s what you should note:
The “result” has L prepended to the recursively constructed remainder.
The recursive call to merge rebuilds the entire second list, using [R|Rs].
It should be possible to build the other clause by looking at this.
As an intermediate Prolog user, I would be naturally a bit suspicious of using two clauses to do this work, because it’s going to create unnecessary choice points. As a beginner, you will be tempted to erase those choice points using cuts, which will go badly for you. A more intermediate approach would be to subsume both of the necessary clauses into one using a conditional operator:
merge([L|Ls], [R|Rs], [N|Ns]) :-
( L #< R ->
N = L, merge(Ls, [R|Rs], Ns)
; —- other case goes here
).
An expert would probably build it using if_/3 instead:
#<(X,Y,true) :- X #< Y.
#<(X,Y,false) :- X #>= Y.
merge([L|Ls], [R|Rs], [N|Ns]) :-
if_(#<(L,R),
(N = L, merge(Ls, [R|Rs], Ns)),
( -- other case here )).
Anyway, I hope this helps illustrate the situation.

Finding the longest list in Prolog?

I need to write a predicate longestList/2 such that longestList(L1,L2) is satisfied if L2 is the longest
nested list from the list of lists L1.
?- longestList([[1],[1,2],[1,2,3],[1,2,3,4]],LI).
LI = [[1, 2, 3, 4]] ;
No
?- longestList([[a,b,c],[d,e],[f,g,h]],LI).
LI = [[f, g, h],[a,b,c]];
No
Could someone please help me with intuition to go about solving it?
Here's an outline for a basic, recursive approach. Not quite as crisp as the answer #CapelliC gave, but on the same order of simplicity.
The idea is to traverse the list and keep track of the longest list you've seen so far, and what it's length is. Then you step through the list recursively and update these arguments for the recursion if the conditions indicate so. It's a slight elaboration on the technique used to do a recursive "max list element" predicate. To do this, you set up a call to include more arguments (the current longest list, and its length).
longestList([], []).
longestList([L|Ls], LongestList) :-
length(L, Length),
% Start with the first element (L) being my best choice so far
longestList(Ls, L, Length, LongestList).
Here is the expanded predicate with the new arguments.
longestList([L|Ls], LongestListSoFar, GreatestLengthSoFar, LongestList) :-
% Here, you need to examine L and determine if it should supersede
% the longest list so far and its length. You need to keep in mind that
% if the length of L is the same as the max length so far, then I
% may choose to keep the LongestListSoFar, or choose L. Both are
% valid solutions for this call. This is a good place to use the `;`
% operator, and to be cautious about parenthesizing expressions since
% the comma has higher precedence than the semi-colon.
% Also, you'll need to make a recursive call to longestList(Ls, ??, ??, LongestList).
% The arguments to the recursion will depend upon which way the decision flow goes.
%
% After all that to-do, don't let it scare you: it's about 5 lines of code :)
%
longestList([], LongestListSoFar, ??, ??).
% Fill in the ??. What should they be at list's end ([])?
% Do I even care now what the 3rd argument is?
Hopefully that's enough to give you something to think about to make progress. Or, use #CapelliC's solution and write the member_length/3 predicate. :) Note that, as in his solution, the above solution would generate each maximum list on backtracking if there are more than one. So, you could use findall/3 if you want to get all the solutions in one list.
member/2 will allow you to peek an element (a list for your case) from a list: so, if you have a member_length/3 predicate, you could code
longestList(Lists, Longest) :-
member_length(Lists, Longest, N),
\+ ( member_length(Lists, _Another, M), M > N ).
then to find all longest, you can use findall/3...
Following code, which uses if else, seem to work partially. It has to be called with 0 length and so one cannot get length itself from here.
longest_list([H|T], LongList, LongLen):-
length(H, Len),
(Len > LongLen ->
longest_list(T, [H], Len);
longest_list(T, LongList, LongLen)).
longest_list([],Finallist,_):-writeln(Finallist).
?- longest_list([[1,2,3], [3,4], [4,5,6,7,8], [5,3,4]], Longestlist, 0).
[[4,5,6,7,8]]
true.
However, the variable itself is not coming:
?- writeln(Longestlist).
_G1955
true.
It may give some ideas.

Cuts in recursion of Prolog

I am learning Prolog myself and recently came across a piece of notes:-
Example: nth/3
for example, to find the nth element of a list we could use
nth([X|_],0,X).
nth([_|L],N,X) :- N1 is N - 1, nth(L,N1,X).
the 0th element of a list is the head of the list (first clause), otherwise
we take the n-1th element of the tail of the list (second clause).
once we have found the nth element, we can’t find any more by backtracking.
nth([X|_],0,X).
nth([_|L],N,X) :- N1 is N - 1, !, nth(L,N1,X).
adding a cut makes this clear and may be necessary for tail recursion
optimisation.
However, when I use the trace function in Prolog, I found out that the calling sequences of these 2 pieces of codes are exactly the same.
Should I put the ! mark as follows instead?
nth([X|_],0,X) :- !.
nth([_|L],N,X) :- N1 is N - 1, nth(L,N1,X).
The cut in the second clause is redundant as there are no more clauses and the goal before it (the is/2 call) is deterministic. I also don't think that the cut plays any role on tail recursion optimization (which basically requires that you recursive call be the last goal in the clause body).
However, before worrying about cut placement, you should check what happens if you call the nth/3 predicate in a mode other than nth(+,+,-). For example, what happens in mode nth(+,+,+), i.e. when you call the predicate with all arguments instantiated, but the element is not in the list? Hint: moving the cut to the first clause will not solve the problem.

Resources