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?

4

2 回答 2

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.
于 2013-04-22T15:59:41.487 回答
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.

于 2013-04-22T15:14:08.280 回答