I have this very simple problem: write a Prolog program that implement the append Prolog function, that concatenate two strings and that work in the following way:
append([a,b],[c,d],X). ---> X = [a,b,c,d]
append([a,b],X,[a,b,c,d]). ---> X = [c,d]
append([a,b],[X,d],[a,b,c,d]). ---> X=c
append(X,Y,[a,b,c,d]). ---> X=[] and Y=[a,b,c,d)
So I have the following two solutions and I am not so sure if my declarative interpretation is correct:
1) SOLUTION 1:
myappend1([],L,L).
myappend1([X|L1],L2,[X|L3]) :- myappend1(L1,L2,L3).
I think that I can read it in a declarative way as following:
The fact say that: if the first list (L1) is empty and the second list (L2) is not empty then it is TRUE that the concatenation of L1*L2 is L2
If the fact it is not true it means that the first list is not empty and so the concatenation of the first list and the second list it is not true that is the second list
So, let me call the first list L1, the second list L2 and the third list L3 then the rule responds TRUE if L3 is the concatenation of L1 and L2, false otherwise
I think that the declarative meaning of this rule is that: the head of the rule is true if the body of the rule is true.
In the head extract the first X element from the L1 list and from L3 list (and try to unify, if it matching go ahead, otherwise it means that the third list it is not the concatenation for the first and the second list)
In the body call the function on the first list without X element, the second list and the L3 list (that represent the concatenation)
When it reach the base case in which I have the demonstrated fact myappend1([],L,L). that is true, the program do backtracking at the previous past and because the X element of the first list unified with the X element of the third list it can do that also this computational pass it is TRUE and go back until reach the first assertion
Is this a correct declarative interpretation?
2) SECOND SOLUTION:
myappend2([],L,L).
myappend2(L1,L2,L3) :- L1=[X|T], % Dimostra questo predicato AND
L3=[X|L4], % Dimostra questo predicato AND
myappend2(T,L2,L4). % Dimostra questa funzione
As in the previous solution the fact simply say that: if the first list (L1) is empty and the second list (L2) is not empty then it is TRUE that the concatenation of L1*L2 is L2
If the fact it is not true it means that the first list is not empty and so the concatenation of the first list and the second list it is not true that is the second list
If the fact it is not true Prolog call the rule and this rule means that: the head of the rule is true if the body of the rule is true.
In this case I can read it in this way:
The concatenation of L1 and L2 is L3 is TRUE if it is true that:
The current first X element of L1 unifies with the current first element of concatenation list and myappend2 called on the first sublist, L2 and the third sublist it is true
Is it correct?
for me it is so difficult reasoning in declarative way :-(
Like last time, you're adding restrictions that aren't present in the code. Don't feel bad about it, Prolog is very different and it will take time to get used to it.
Let's start.
append([], L, L).
You said:
If the first list (L1) is empty and the second list (L2) is not empty then it is TRUE that the concatenation of L1*L2 is L2
In fact this rule says nothing about whether L2 is empty--or even a list!--or not. It simply says that the empty list appended to something else is that something else. Observe:
?- append([], foo, X).
X = foo.
The declarative reading here is "the empty list appended to L is L."
If the fact it is not true it means that the first list is not empty and so the concatenation of the first list and the second list it is not true that is the second list
Yes, this is correct, but Prolog isn't probing that deeply into the body. It just says "the first list is not empty, so this rule does not match; moving on."
The next rule:
myappend1([X|L1], L2, [X|L3]) :- myappend1(L1,L2,L3).
Your commentary seems excessively complex to me. I would say that this rule says: "myappend1 of the list [X followed by L1] to L2 is the list [X followed by L3], if myappend1 of the list L1 to L2 is L3." The consequences of this reading, however, are exactly as you describe.
Your understanding of what is happening in the first version is, therefore, correct.
The second solution is, mechanically, exactly the same as the first solution. The only difference is that we have moved the unification from the head of the clause into the body. This version is, to my eyes, clearly inferior, because all it has done is create extra work for the reader.
I think the problem you're having, so far, is that your declarative reasoning is intimately tied up with Prolog's engine of computation. A purer declarative reading like the ones I have supplied are simpler and look more like what the Prolog is saying (and have less to do with how it is evaluated).
It will take practice for you to separate these notions, but I think it will help you get better (clearly it's something you're concerned about). In the meantime there's nothing wrong with coming here and asking for help like you've been doing when you get confused. :)
Let me know if I can help more!
When you try to figure out the declarative meaning of a predicate, you are asking: For which solutions does this predicate hold?
Prolog's1 clauses contribute to the set of solutions independently. So making any connections between the clauses needs some extra scrutiny. It is very easy to make some assumptions that are not the case:
myappend1([],L,L).
If the fact it is not true it means that the first list is not empty and so ...
Consider a goal, myappend1([],[],[a]). The fact does not apply, still the first list is empty. Here, you are attempting to operationalize the meaning of the clause. It is very tempting to do this since the largest part of programming languages can only be understood by imagining how something happens step-by-step. The difficulty in Prolog lies in trying to ignore such details, without entirely ignoring procedural aspects.
myappend1([X|L1],L2,[X|L3]) :- myappend1(L1,L2,L3).
To read rules, in particular recursive rules, it is helpful to look at the :- which is a 1970s rendering of ← . So it is an arrow, but it goes from right-to-left. Therefore, you can read this rules as follows, starting with the right-hand-side:
Provided that myappend(L1,L2,L3) holds, now cross the :- over to the left side also myappend([X|L1],L2,[X|L3]) holds.
Sometimes, an even better way to read such a rule is to cover the head completely and ask
??? :- myappend1(L1,L2,L3).
Assume, I know some L1, L2, L3 that hold for myappend1(L1,L2,L3). what can I conclude out of this? Is there anything interesting? Is there anything related I can construct easily out of those 3 values?
This is something which is in the beginning a bit revolting, because you might say: But how do I know that such exists? Well, you don't. You are only assuming it exists. If it will never exist, then you will never be able to make that conclusion.
Many try to read the rules left-to-right, but while Prolog is actually executing them left-to-right, the meaning they cover is easier to understand going in the direction of the conclusion. When Prolog executes a rule left-to-right it does not know if this will work out or not. So the execution might be of entirely speculative nature. Think of append(L1,[z],[a,b,c,d,e]). Here, Prolog will apply this rule for each element of the list. But all such application is in vain. That is, ultimately it will fail.
Fine print
1 Actually, the pure, monotonic subset of Prolog.
Related
I'm trying to write Prolog logic for the first time, but I'm having trouble. I am to write logic that takes two lists and checks for like elements between the two. For example, consider the predicate similarity/2 :
?- similarity([2,4,5,6,8], [1,3,5,6,9]).
true.
?- similarity([1,2,3], [5,6,8]).
false.
The first query will return true as those two lists have 5 and 6 in common. The second returns false as there are no common elements between the two lists in that query.
I CANNOT use built in logic, such as member, disjoint, intersection, etc. I am thinking of iterating through the first list provided, and checking to see if it matches each element in the second list. Is this an efficient approach to this problem? I will appreciate any advice and help. Thank you so much.
Writing Prolog for the first time can be really daunting, since it is unlike many traditional programming languages that you will most likely encounter; however it is a very rewarding experience once you've got a grasp on this new style of programming! Since you mention that you are writing Prolog for the first time I'll give some general tips and tricks about writing Prolog, and then move onto some hints to your problem, and then provide what I believe to be a solution.
Think Recursively
You can think of every Prolog program that you write to be intrinsically recursive in nature. i.e. you can provide it with a series of "base-cases" which take the following form:
human(John). or wildling(Ygritte) In my opinion, these rules should always be the first ones that you write. Try to break down the problem into its simplest case and then work from there.
On the other hand, you can also provide it with more complex rules which will look something like this: contains(X, [H|T]):- contains(X, T) The key bit is that writing a rule like this is very much equivalent to writing a recursive function in say, Python. This rule does a lot of the heavy lifting in looking to see whether a value is contained in a list, but it isn't complete without a "base-case". A complete contains rule would actually be two rules put together: contains(X, [X|_]).
contains(X, [H|T]):-contains(X, T).
The big takeaway from this is to try and identify the simple cases of your problem, which can act like base cases in a recursive function, and then try to identify how you want to "recurse" and actually do work on the problem at hand.
Pattern Matching
Part of the great thing about Prolog is the pattern matching system that it has in place. You should 100% use this to your advantage whenever you can -- it is especially helpful when trying to do anything with lists. For example:
head(X, [X|T]).
Will evaluate to true when called thusly: head(1, [1, 2, 3]) because intrinsic in the rule is the matching of X. This sort of pattern matching on the first element of a list is incredibly important and really the key way that you will do any work on lists in Prolog. In my experience, pattern matching on the head of a list will often be one of the "base-cases" that I mentioned beforehand.
Understand The Flow of the Program
Another key component of how Prolog works is that it takes a "top-down" approach to reading code. What I mean by that is that every time a rule is called (except for definitions of the form king(James).), Prolog starts at line 1 and continues until it reaches a rule that is true or the end of the file. Therefore, the ordering of your rules is incredibly important. I'm assuming that you know that you can combine rules together via a comma to indicate logical AND, but what is maybe more subtle is that if you order one rule above another, it can act as a logical OR, simply because it will be evaluated before another rule, and can potentially cause the program to recurse.
Specific Example
Now that I've gotten all of my general advice out of the way, I'll actually reference the given problem. First, I'd write my "base-case". What would happen if you are given two lists whose first elements are the same? If the first element in each list is not the same, then they have to be different. So, you have to look through the second list to see if this element is contained anywhere in the rest of the list. What kind of rule would this produce? OR it could be the case that the first element of the first list is not contained within the second at all, in which case you have to advance once in the first list, and start again with the second list. What kind of rule would this produce?
In the end, I would say that your approach is the correct one to take, and I have provided my own solution below:
similarity([H|_], [H|_]).
similarity(H1|T1], [_|T2]):- similarity([H1|T1], T2).
similarity([_|T1], [H2|T2]):- similarity(T1, [H2|T2]).
Hope all of this helps in some way!
I currently working on some prolog problems, one is "subBag(x, y) tests whether x, considered as a bag, is a subbag of y". My code doesn't work at all and always true. Here is my code.
delete(X,[],[]).
delete(X,[X|T],T).
delete(X,[H|T],[H|Result]):-
delete(X,T,Result).
subBag([],[]).
subBag([],[H|T]).
subBag([X|S],[H|T]):-
member(X,[H|T]),
delete(X,[H|T],Result),
subBag(S,Result).
Thank you.
What is a subbag? I take that to mean, all the items in the subbag are present in at least the same quantities as they are in the containing bag. To state it inductively, let's break it into two cases: the case where I have an empty list. Is that a subbag? Yes, of any list:
subbag([], Bag) :- is_list(Bag).
Now, the inductive case. Let's break the subbag into an item and the rest of the subbag. If this item can be removed from the containing bag, and the rest form a subbag of the remainder from the containing bag, then we have a subbag. Like so:
subbag([X|Subbag], Bag) :-
select(X, Bag, RemainingBag),
subbag(Subbag, RemainingBag).
The magic predicate select/3 is a hugely useful utility here, allowing you in one statement to say X is in Bag, and the rest of the bag is in RemainingBag. This kind of situation seems to come up all the time in processing lists in Prolog. (Note that in the SWI Prolog documentation, there is often a little orange :- icon next to the name, which will take you to the source code for that predicate, in case you've been given a stupid requirement not to use a built-in predicate by a clueless professor.)
I want to warn you that the efficiency of this solution is not great, but I actually think the nature of this problem might just be that way. The number of solutions you'll obtain from an query (like subbag(X, [1,2,3,4,5])) is going to be large; I found it to be essentially the number of permutations of a set, using the OEIS (sequence A000522).
I dont understand completely how your code should work, but i think that there is for sure too much splitting into head and tail in places where it is not necessary.
Maybe this predicate will help you to solve your problem.
isSublist(Sublist,List) :-
append([_,Sublist,_],List).
This predicate uses append/2 build-in predicate, read about it here
I have a list L and I need to split each element into a separate list and again append them together. This is the code I made for the same.
split([],[]).
split([H|T],Ls):-split(T,Ls),splist(H,[]).
make(Val,[H1|List],[H1|Res]):- make(Val,List,Res). make(Val, List,[Val|List]).
splist(H,L2):- make(Sum,[],L1),append(L1,L2,NewL).
When I use this code, each element of L is passed recursively from split() to splist() and made into a list L1 with single element by make(). I need append to keep concatenating L1 and L2. But it does not so so
For example, I have L=[1,2,3]. Now I need the following process to be done.
H=1, L1=[1] and L2=[1]. Next H=2, L1=[2] and L2=[1,2]. Next H=3, L1=[3] and L2=[1,2,3].
I need the output as mentioned above, but this is what my code does.
H=1, L1=[1], and L2= [1]. Next H=2, L1=[2] and L2=[2]. Next H=3, L1=[3] and L2=[3].
I can't make any sense out of your code. make definition is incomplete. As is, it does nothing and then fails.
Your split is equivalent to split(X,[]):- reverse(X,R), maplist(spl([]),R). with spl(B,A):-splist(A,B)., i.e. it tries splist(H,[]) for each element H of the input list X, backwards, to see whether it fails or not - that's its only outcome, as the arguments are fixed - H and [].
naming your predicates split and splist is a very bad idea - we humans are wired to distinguish words from their start, and the only different letter in these names is hidden way far near the end. IOW the two names are very similar, and it is very easy to misread and mistype them.
lastly, for splist(H,L2):- make(Sum,[],L1),append(L1,L2,NewL)., since make cn only fail, so will splist. But even if make were to produce something in L1 out of thin air - Sum starts out uninstantiated mind you - what does it say about L2? That it can be appended to the list L1? Any list can be appended to any other, saying that is saying nothing.
?? :)
I have some problem to join declarative reasoning...so I am here to ask you if my reasoning is correct or if there is something wrong or if I am missing something...
I have the following problem: Write a Prolog program that invert the element of a list
for example if I call something like:
myreverse([a,b,c,d,e],X). I have to obtain that X=[e,d,c,b,a]
I have the following solution:
naiverev([],[]).
naiverev([H|T],R):- naiverev(T,RevT),
append(RevT,[H],R).
This is my interpretation:
I have a fact that say that the inverse of an empty list is an empty list.
If the first list it is not empty, the fact it is not true and the fact it is not match so move on to the next rule.
The rule say that: the program that prove that the list R is the inverse of the list [H|T]
I can read the logic implication from right to left in the following way:
IF it is TRUE that naivrev(T, RevT) AND append(RevT, [H], R) ---> naivrev([H|T],R) it is TRUE
So (in the body of the rule) I am assuming that the "function" naivrev(T,RevT) respond TRUE if RevT is the inverse of T, FALSE otherwise.
At the same time I am assuming* that **append(RevT,[H],R) respond TRUE if R is [H|RevT], FALSE otherwise.
Then, if both the parts of the rule body are TRUE, the program can infer that the HEAD is TRUE (in this case that R is the inverse of [H|T])
Is this reasoning good or I am missing something?
Like the last two times, you have again intermixed Prolog's engine of computation with the purely declarative reading. Whenever you say, procedurally "the rule is not matched so move on" or anything like that, you're invoking Prolog's algorithm to explain what's going on, not logic. But you're getting better, because the rest of your stuff is much closer than before.
Rule 1: the reverse of the empty list is the empty list. (Same as you have.)
Rule 2: the reverse of [H|T] is the reverse of T, called RevT, appended to the list [H].
What makes this work, of course, is that Prolog will try rule 1, when it doesn't match, it will try rule 2, and recursively build up the result (in a tremendously inefficient way, as you probably realize). But this "making it go" of checking rules and choosing between them and how that process is performed, is what Prolog adds to a declarative or logical statement.
Your reading of the logical implication is correct: If naiverev(T, RevT) is true and append(RevT, [H], R) is true, then naiverev([H|T], R) is true. This is just as #false explained in your previous question, so I would say you're definitely starting to get it. Your remarks about the body being true leading to the head being true are spot on.
So good job, it looks like you're getting it. :)
I have a question I would like to ask you something about a code snippet:
insert_pq(State, [], [State]) :- !.
insert_pq(State, [H|Tail], [State, H|Tail]) :-
precedes(State, H).
insert_pq(State, [H|T], [H|Tnew]) :-
insert_pq(State, T, Tnew).
precedes(X, Y) :- X < Y. % < needs to be defined depending on problem
the function quite clearly adds an item to a priority queue. The problem I have is the cut off operator in the first line. Presumably whenever the call reaches this line of code this is the only possible solution to the query, and the function calls would simply unwind (or is it wind up?), there would be no need to back track and search for another solution to the query.
So this cut off here is superfluous. Am I correct in my deduction?
Yes, any half-decent Prolog compiler will notice that there is no other clause where the second argument is an empty list.
It would be more useful at the end of the second clause, though I'd rather combine the second and the third clause and use a local cut (precedes(...) -> ... ; ...).
The particular technique that the compiler users to eliminate candidate predicates for matching is called argument indexing. Different prolog implementations could potentially index different numbers of arguments by default.
So if you're worried about whether an argument is being indexed or not, you should check how many arguments the prolog you're using indexes. According to the SWI reference manual it only indexes the first argument by default. So in your case the cut is actually not redundant. You can however explicitly stipulate which arguments should be indexed using the predicates index/1 and hash/1 which are linked to in the above link.
Or you could just reorder the arguments, or you could just keep the cut.
Yes, you are correct. Even if the compiler isn't half-decent (which SWI Prolog certainly is), the worst it can do is match the second and third clauses, which will fail immediately.
However, if the second clause matches, the third does as well. Is this the intended behaviour?