Re: Prolog type overloading
- From: Jussi Piitulainen <jpiitula@xxxxxxxxxxxxxxxx>
- Date: 28 Jun 2006 13:54:59 +0300
George writes:
....
As an example, I have a predicate that tells me who is to play next
in a game. If I have in my database next([john,peter]), it means
that john and peter are next to make a move.
I would like to define a predicate with the same name (next) but
with the following logic: if next succeeds with a list, check
whether the player I pass as an argument is member of that list. I
wrote it as:
next(P):-
next([S]),
member(P,[S]).
However, this results in infinite looping. Is there a better of
doing it or telling Prolog not to invoke next without a list as the
parameter?
The better way is to use different names for different
predicates.
You can add the condition that P is not a non-empty list:
next(P) :-
P \= [_|_],
next([S]),
member(P,[S]).
You will find that [S] does not unify with [john,peter].
Replace [S] with [T,U], maybe.
Then you will find that this clause will fail when P is a
variable. You can add that possibility to the condition:
next(P) :-
( var(P) ; P \= [_|_] ),
next([T,U]),
member(P,[T,U]).
Hm. You could have replaces [S] with just V. How about that:
next(P) :-
( var(P) ; P \= [_|_] ),
next(V),
member(P,V).
Now a call next(W) unifies with next([john,peter]) in your
database, but it also unifies with the head of the the rule
for finding the members of [john,peter], and then there is
the call next(V) in the body, and the unbounded recursion
that you noticed. But we can be clever! Switch the clauses
in the body:
next(P) :-
( var(P) ; P \= [_|_] ),
member(P,V),
next(V).
Now member(P,V) binds V to [P|_], [_,P|_], [_,_,P|_]
(on backtracking) so that next(V) only succeeds for the
next([john,peter]) clauses. Pity that we introduced
another unbounded recursion in backtracking to member(P,V).
It's not always clever to be clever. Back to [T,U].
Then you will find other things that you want to call next/1.
Your program starts to get more complex, fast. Good luck.
I would use different names for different predicates.
.
- Follow-Ups:
- Re: Prolog type overloading
- From: Lekeas GK
- Re: Prolog type overloading
- References:
- Prolog type overloading
- From: George
- Prolog type overloading
- Prev by Date: Prolog type overloading
- Next by Date: Re: Prolog type overloading
- Previous by thread: Prolog type overloading
- Next by thread: Re: Prolog type overloading
- Index(es):
Relevant Pages
|
|