3

I'm trying to write an element handling function in Prolog. It's almost the same as the prolog predicate member/2 but it must do the job in a different way. For being specific; I must say the member/2 predicate function is this:

member(X, [X|_]).
member(X, [_|Tail]) :-
   member(X,Tail).

When you give a query for example: member(X, [1,2,3]).

It gives you X = 1; X = 2; X = 3; in this order for all redo's. I want an element function almost the same. I want the same result with the member function when I give a query like this:

element(X, (1,2,3)).

The difference is just parenthesis instead of bracekts like these : []
In order to do this I tried that:

element(X, (X,_)).
element(X, (_,Tail)) :-
   element(X,Tail).

Which is exactly the same as member/2 predicate function implementation. But this doesn't work because it doesn't giving the last element which is X=3. So I added one more fact that is:

element(X, X).

But this doesn't work either because (obviously) it is giving unnecessary answer with real elements like these:

X=(1,2,3)
X=(2,3)

How can I handle this?

false
  • 10,264
  • 13
  • 101
  • 209

2 Answers2

3

Seems that a cut can solve your problem:

element(X, (X, _)).
element(X, (_, Tail)) :-
    !, element(X, Tail).
element(X, X).

test:

?- element(X, (1,2,3)).
X = 1 ;
X = 2 ;
X = 3.

?- element(2, (1,2,3,2)).
true ;
true.
CapelliC
  • 59,646
  • 5
  • 47
  • 90
  • Thank you very much, I'm so embarrased that I couldn't see this. I tried to use a cut but because I'm very new to prolog I couldn't place it properly where it's necessary. I'm trying to figure out how prolog works for different situations by the trace option while testing but I couldn't really understand what cut (!) operator does. Can anybody explain it in a proper way? Thanks a lot for the answer again. – Hazım Türkkan Apr 23 '13 at 09:09
  • I found an explanation like this and it looks good; I could understand now some more but for usage I must get used to it: [link](http://en.wikipedia.org/wiki/Cut_(logic_programming). – Hazım Türkkan Apr 23 '13 at 09:17
1

Terms like (1,2,3) in Prolog have commas as their primary functor. Probably you want to use operator univ, denoted by infix =.., or its close relations functor/3 and arg/3 to pick apart these tuples.

Community
  • 1
  • 1
hardmath
  • 8,753
  • 2
  • 37
  • 65