I have a list of pairs and want to find the element with the corresponding first value.
?- findconn1(9, [(9,[23,33]),(42,[21,322])], R).
So in this case I want the result to be (9,[23,23])
in R
.
The code is
findconn(X, [], R).
findconn(X, [(H,T)|Y], R) :-
member(X, H),
findConn(X, Y),
append(T, T, R).
It always returns false
despite that the element is present. And also is there any other way to return as I'm quite new to Prolog.
Here is a simple way using built-in member/2
predicate:
findconn1(X,L,(X,L1)):- member((X,L1),L).
Example:
?- findconn1(9,[(9,[23,33]),(42,[21,322])],R).
R = (9, [23, 33]) ;
false.
With the above solution note that if 9 exists more than once you get all solutions:
?- findconn1(9,[(9,[23,33]),(42,[21,322]),(9,[1,2])],R).
R = (9, [23, 33]) ;
R = (9, [1, 2]).
Well, you don't need member/2
. Just use pattern matching with a base case and a recursion case like this:
findconn1(N,[(N,B)|_],N-B). %basecase
findconn1(N,[(_,_)|T],R):-
findconn1(N,T,R).
So when you type a query:
?- findconn1(42,[(9,[23,33]),(42,[21,322])],R).
R = 42-[21, 322]
You get result in R.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With