Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog; find list item

Tags:

list

prolog

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.

like image 324
Coder Avatar asked Mar 08 '23 09:03

Coder


2 Answers

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]).
like image 136
coder Avatar answered Mar 12 '23 05:03

coder


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.

like image 44
Luai Ghunim Avatar answered Mar 12 '23 04:03

Luai Ghunim