4
votes

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.

2
YOu don't need to use member/2, use pattern matching.Luai Ghunim
How would I do thatCoder
@Coder. Why did you delete your answer? It is clearly superior to the other answer, which is basically a specialized boilerplate reimplementation of member/2...repeat
@coder. Good! Next time, don't delete. Let SO work. Let the votes/comments/edits speak...repeat
@repeat, Ok thanks, for the comment!!!coder

2 Answers

5
votes

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]).
2
votes

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.