Prolog: remove member of list with non-instantiated values - list

I want remove all appearences of an element on a list, similar to this, but in my case, the list may have non-instantiated variables. For example:
delMember(z, [A,B,A,z], L).
L = [A, B, A];
false.
and
delMember(A, [A, B, A, z], L).
L = [B,z];
false.
I tried defining delMember as the following:
delMember(_, [], []).
delMember(X, [X|Xs], Y) :- delMember(X, Xs, Y).
delMember(X, [T|Xs], [T|Y]) :- X \== T, delMember(X, Xs, Y).
With this definition, the last result I get is correct but it's still trying to instantiate the variables before that.
?- delMember(A, [A,B,A,z], R).
A = B, B = z,
R = [] ;
A = B,
R = [z] ;
A = z,
R = [B] ;
R = [B, z] ;
any ideas???

If you look at your second predicate clause:
delMember(X, [X|Xs], Y) :- delMember(X, Xs, Y).
Unification is occurring with the X in the first and second arguments. This leads to the results you are observing when you do your query. You need to apply the same operator as you did in your third clause. So your complete predicate (with some slightly changed variable names to be more conventional) would look like:
delMember(_, [], []).
delMember(X, [X1|Xs], Ys) :- X == X1, delMember(X, Xs, Ys).
delMember(X, [X1|Xs], [X1|Ys]) :- X \== X1, delMember(X, Xs, Ys).

Related

Prolog - Finding adjacent elements in a list

I'm trying to define a predicate adjacent(X, Y, Zs) that is true if X and Y are adjacent in a list. My code is currently this:
adjacent(_, _, []).
adjacent(X, Y, [X, Y|Tail]) :-
adjacent(X,Y, Tail).
It works for the basic case of adjacent(c, d, [a, b, c, d, e]), but due to the base case, every other case returns true as well, and I'm stuck on that.
The other problem is that if X is not equal to the first part of the list's head, then it skips past both X and Y and goes to the next 'X'; e.g., if c isn't equal to a, then it skips past both a and b and checks if c is equal to c. This is problematic when, for example, the list is
[a, c, d, e]
because it ends up never checking c (I believe).
I'm pretty lost on how to reconcile the two issues and turn my logical understanding of what needs to occur into code.
EDIT: Thanks to Christian Hujer's answer, my base case mistake has been corrected, so now I'm just stuck on the second issue.
In the original solution attempt:
adjacent(_, _, []).
adjacent(X, Y, [X, Y|Tail]) :-
adjacent(X,Y, Tail).
As #ChristianHujer points out, the first clause should not be there because it isn't true. The empty list should have no adjacent elements.
The second clause is also problematic. It shows that X and Y are adjacent in the list, but then recurses and doesn't just succeed. A proper clause should be:
adjacent(X, Y, [X,Y|_]).
Which says that X and Y are adjacent in the list if they're the first two elements in the list, regardless of what the tail is. This also forms a proper base case. Then your general, recursive clause should take care of the rest of the cases:
adjacent(X, Y, [_|Tail]) :-
adjacent(X, Y, Tail).
This says that X and Y are adjacent in [_|Tail] if they're adjacent in Tail. This takes care of the second problem you were encountering.
Thus, the whole solution would be:
adjacent(X, Y, [X,Y|_]).
adjacent(X, Y, [_|Tail]) :-
adjacent(X, Y, Tail).
This will succeed as many times as X and Y appear together, in that order, in the list.
This is also naturally solvable with a DCG (although #repeat's append/3 based solution is more concise):
adjacent(X, Y) --> ..., [X, Y], ... .
... --> [] | [_], ... .
adjacent(X, Y, L) :- phrase(adjacent(X, Y), L).
| ?- adjacent(b, c, [a,b,c,d]).
true ? a
(1 ms) no
| ?-
I think your base case is wrong. In your situation, you want recursion to terminate with a false predicate, not with a true predicate. And it's logical: In an empty list, there are no adjacent elements. Never.
In this answer we try to keep it simple—by building on append/3:
adjacent(E0, E1, Es) :-
append(_, [E0,E1|_], Es).
Sample query:
?- adjacent(X, Y, [a,b,c,d,e]).
X = a, Y = b ;
X = b, Y = c ;
X = c, Y = d ;
X = d, Y = e ;
false.
The auxiliary predicate adjacent_/5 always "lags behind" by exactly two (list items):
adjacent(X0, X1, [E0,E1|Es]) :-
adjacent_(Es, E0, E1, X0, X1).
adjacent_([], E0, E1, E0, E1).
adjacent_([E2|Es], E0, E1, X0, X1) :-
if_(E0+E1 = X0+X1,
true,
adjacent_(Es, E1, E2, X0, X1)).
Using SWI-Prolog we run:
?- set_prolog_flag(double_quotes, chars).
true.
?- adjacent(a, b, "abab").
true.
?- adjacent(b, c, "abcd").
true.
?- adjacent(X, Y, "abcd").
X = a, Y = b
; X = b, Y = c
; X = c, Y = d.
Edit
The corrected definition of adjacent_/5 gives right answers for the following queries, too:
?- adjacent(X, X, [A,B,C]).
X = A, A = B
; X = B, B = C, dif(f(C,C),f(A,A)).
?- adjacent(a, X, "aab").
X = a
; X = b.
?- adjacent(a, b, "aab").
true.
Here is a definition that I believe is in the long term preferable to #repeat's solution:
adjacent(X0, X1, [E0,E1|Es]) :-
adjacent_(Es, E0, E1, X0, X1).
adjacent_([], E0, E1, E0, E1).
adjacent_([E2|Es], E0, E1, X0, X1) :-
if_(( E0 = X0, E1 = X1 ),
true,
adjacent_(Es, E1, E2, X0, X1)).
Using a reified and:
','(A_1, B_1, T) :-
if_(A_1, call(B_1, T), T = false).
;(A_1, B_1, T) :-
if_(A_1, T = true, call(B_1, T)).

Apply predicate on every list element

I need to implement y = 1/x on a list of numbers.
I.e.
inv (List1, ResultingList).
inv ([2 , 1 , 0 , 0.25 ] , R).
R = [ 0.5, 1, inf, 4.0 ].
I've try with a recursive function but it doesn't work.
this is my "solution":
inv([], []).
inv(list, R):- list == [H|T], T \== [], Y is (1/H),
append(R, Y, R), inv(T);
list = [H|T], T == [], R = T;
list = [H|T], H == [0], append(R, "inf", R).
I know that there are a lot of mistakes but I don't find the way.
Variable names start with a capital letter, and (==)/2 is only used for very rare cases. Further append/3 is rarely used for such predicates. Briefly:
inv([], []).
inv([X|Xs], [Y|Ys]) :-
Y is 1/X,
inv(Xs, Ys).
Or:
reciprocal(X, Y) :-
Y is 1/X.
inv(Xs, Ys) :-
maplist(reciprocal, Xs, Ys)
or using library(lambda)
inv(Xs, Ys) :-
maplist(\X^Y^(Y is 1/X), Xs, Ys).
note that most commonly maplist/3 is called directly without the auxiliary definition.
There is, however, no standard for the usage of a continuation value inf. In case you really need it, you have have to make that extra handling yourself.

Prolog. Sum of the elements of two lists of different length

Please help me!
I need to find sum of the elements of two lists of different length.
It should look like:
?-p([1,2,3],[1,2,3,9],L),write(L),nl.
L = [2,4,6,9].
p([],_,[]).
p(_,[],[]).
p([H1|T1],[H2|T2],[H|T]):-H is H1 + H2,p(T1,T2,T).
?-p([1,2,3],[1,2,3],L),write(L),nl.
So I've got some troubles with different length of lists. I don't know how to do it.
Thanks for your help! Tanya.
I prefer shorter, deterministic code, where possible:
p([X|Xs], [Y|Ys], [Z|Zs]) :-
Z is X + Y,
!, p(Xs, Ys, Zs).
p([], Ys, Ys) :- !.
p(Xs, [], Xs).
This should work:
p([], [], []).
p([], [H2|T2], [L|Ls]) :-
L = H2,
p([], T2, Ls).
p([H1|T1], [], [L|Ls]) :-
L = H1,
p(T1, [], Ls).
p([H1|T1], [H2|T2], [L|Ls]) :-
L is H1 + H2,
p(T1, T2, Ls).
Explanation:
As long as there are elements in both lists, they get added and 'prepended' to L. Whenever there is 1 list empty, it will just 'prepend' them to L without adding it. When both are empty, the recursivity stops.

Prolog substitution

How can I replace a list with another list that contain the variable to be replaced. for example
rep([x, d, e, z, x, z, p], [x=z, z=x, d=c], R).
R = [z, c, e, x, z, x, p]
the x to z and z doesn't change after it has been replaced.
so far I did only the one without the list
rep([], _, []).
rep(L1, H1=H2, L2) :-
rep(L1, H1, H2, L2).
rep([],_,_,[]).
rep([H|T], X1, X2, [X2|L]) :-
H=X1,
rep(T,X1,X2,L),
!.
rep([H|T],X1,X2,[H|L]) :-
rep(T,X1,X2,L).
If you use SWI-Prolog, with module lambda.pl found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl you can write :
:- use_module(library(lambda)).
rep(L, Rep, New_L) :-
maplist(\X^Y^(member(X=Z, Rep)
-> Y = Z
; Y = X), L, New_L).
You should attempt to keep the code simpler than possible:
rep([], _, []).
rep([X|Xs], Vs, [Y|Ys]) :-
( memberchk(X=V, Vs) -> Y = V ; Y = X ),
rep(Xs, Vs, Ys).
Of course, note the idiomatic way (thru memberchk/2) to check for a variable value.
Still yet a more idiomatic way to do: transforming lists it's a basic building block in several languages, and Prolog is no exception:
rep(Xs, Vs, Ys) :- maplist(repv(Vs), Xs, Ys).
repv(Vs, X, Y) :- memberchk(X=V, Vs) -> Y = V ; Y = X .
Here's how you could proceed using if_/3 and (=)/3.
First, we try to find a single Key in a list of pairs K-V.
An extra argument reifies search success.
pairs_key_firstvalue_t([] ,_ ,_ ,false).
pairs_key_firstvalue_t([K-V|KVs],Key,Value,Truth) :-
if_(K=Key,
(V=Value, Truth=true),
pairs_key_firstvalue_t(KVs,Key,Value,Truth)).
Next, we need to handle "not found" cases:
assoc_key_mapped(Assoc,Key,Value) :-
if_(pairs_key_firstvalue_t(Assoc,Key,Value),
true,
Key=Value).
Last, we put it all together using the meta-predicate maplist/3:
?- maplist(assoc_key_mapped([x-z,z-x,d-c]), [x,d,e,z,a,z,p], Rs).
Rs = [z,c,e,x,a,x,p]. % OK, succeeds deterministically
Let's improve this answer by moving the "recursive part" into meta-predicate find_first_in_t/4:
:- meta_predicate find_first_in_t(2,?,?,?).
find_first_in_t(P_2,X,Xs,Truth) :-
list_first_suchthat_t(Xs,X,P_2,Truth).
list_first_suchthat_t([] ,_, _ ,false).
list_first_suchthat_t([E|Es],X,P_2,Truth) :-
if_(call(P_2,E),
(E=X,Truth=true),
list_first_suchthat_t(Es,X,P_2,Truth)).
To fill in the "missing bits and pieces", we define key_pair_t/3:
key_pair_t(Key,K-_,Truth) :-
=(Key,K,Truth).
Based on find_first_in_t/4 and key_pair_t/3, we can write assoc_key_mapped/3 like this:
assoc_key_mapped(Assoc,Key,Value) :-
if_(find_first_in_t(key_pair_t(Key),_-Value,Assoc),
true,
Key=Value).
So, does the OP's use-case still work?
?- maplist(assoc_key_mapped([x-z,z-x,d-c]), [x,d,e,z,a,z,p], Rs).
Rs = [z,c,e,x,a,x,p]. % OK. same result as before
Building on find_first_in_t/4
memberd_t(X,Xs,Truth) :- % memberd_t/3
find_first_in_t(=(X),_,Xs,Truth).
:- meta_predicate exists_in_t(2,?,?). % exists_in_t/3
exists_in_t(P_2,Xs,Truth) :-
find_first_in_t(P_2,_,Xs,Truth).
I find your code rather confused. For one thing, you have rep/3 and rep/4, but none of them have a list in the second position where you're passing the list of variable bindings. H1=H2 cannot possibly match a list, and that's the only rep/3 clause that examines the second argument. If this is a class assignment, it looks like you're a little bit behind and I'd suggest you spend some time on the previous material.
The solution is simpler than you'd think:
rep([], _, []).
rep([X|Xs], Vars, [Y|Rest]) :- member(X=Y, Vars), rep(Xs, Vars, Rest).
rep([X|Xs], Vars, [X|Rest]) :- \+ member(X=_, Vars), rep(Xs, Vars, Rest).
We're using member/2 to find a "variable binding" in the list (in quotes because these are atoms and not true Prolog variables). If it's in the list, Y is the replacement, otherwise we keep using X. And you see this has the desired effect:
?- rep([x, d, e, z, x, z, p], [x=z, z=x, d=c], R).
R = [z, c, e, x, z, x, p] ;
false.
This could be made somewhat more efficient using "or" directly (and save us a choice point):
rep([], _, []).
rep([X|Xs], Vars, [Y|Ys]) :-
(member(X=Y, Vars), ! ; X=Y),
rep(Xs, Vars, Ys).
See:
?- rep([x, d, e, z, x, z, p], [x=z, z=x, d=c], R).
R = [z, c, e, x, z, x, p].

Prolog lists difference

I'm trying to make program in prolog that will do something like this:
diffSet([a,b,c,d], [a,b,e,f], X).
X = [c,d,e,f]
I wrote this:
diffSet([], _, []).
diffSet([H|T1],Set,Z):- member(Set, H), !, diffSet(T1,Set,Z).
diffSet([H|T], Set, [H|Set2]):- diffSet(T,Set,Set2).
But in that way I can only get elements from the first list. How can I extract the elements from the second one?
#edit:
member is checking if H is in Set
member([H|_], H).
member([_|T], H):- member(T, H).
There is a builtin that remove elements from the list:
diffSet([], X, X).
diffSet([H|T1],Set,Z):-
member(H, Set), % NOTE: arguments swapped!
!, delete(T1, H, T2), % avoid duplicates in first list
delete(Set, H, Set2), % remove duplicates in second list
diffSet(T2, Set2, Z).
diffSet([H|T], Set, [H|Set2]) :-
diffSet(T,Set,Set2).
Or using only built-ins. if you wanted to just get the job done:
notcommon(L1, L2, Result) :-
intersection(L1, L2, Intersec),
append(L1, L2, AllItems),
subtract(AllItems, Intersec, Result).
?- notcommon([a,b,c,d], [a,b,e,f], X).
X = [c, d, e, f].
Deliberately avoiding the built ins for this that #chac mentions, this is an inelegant way that does the job.
notcommon([], _, []).
notcommon([H1|T1], L2, [H1|Diffs]) :-
not(member(H1, L2)),
notcommon(T1, L2, Diffs).
notcommon([_|T1], L2, Diffs) :-
notcommon(T1, L2, Diffs).
alldiffs(L1, L2, AllDiffs) :-
notcommon(L1, L2, SetOne),
notcommon(L2, L1, SetTwo),
append(SetOne, SetTwo, AllDiffs).
? alldiffs([a,b,c,d], [a,b,e,f], X).
X = [c, d, e, f] .