Reputation: 47
In prolog I have two rules gender(male,[man,boy]).
and gender(female,[woman,girl]).
as well as having gen(female)
and gen(male)
. I then pass in a variable to see what the user has inputted as follows:
whatgender(X):-
gen(X).
whatgender(X):-
gender(Pass,Out),
member(X,Out).
Pass
is now what I want X
to be. Unfortunately due to how I manipulate it after this I need the variable to be X and can't create another variable to Out e.g. whatgender(X,Pass)
. Is there any way to do this or am I going to have to use a different approach?
Thanks for any help you can provide.
Upvotes: 2
Views: 858
Reputation: 58254
In Prolog, once a variable is instantiated (assigned a specific value) within a given predicate clause, it cannot be reassigned except through backtracking. In other words, this would always fail:
foo(X) :- X = b.
?- X = a, foo(X).
It fails because a
and b
are two different atoms, and foo
attempts to unify a
with b
. This is more clearly seen if you simply queried foo(a)
. How would foo
possibly rebind a value of b
to an atom a
? It's not even meaningful.
A fundamental issue is that your predicate is trying to treat a single variable two different ways. One way to resolve this is to refactor whatgender
so that it means the same thing in both case. We can do this by using two arguments:
whatgender(X, X) :-
gen(X).
whatgender(X, Y) :-
gender(Y, Out),
member(X, Out).
Now, whatgender(X, Y)
means that Y
is the specific gender represented by X
. The first clause is the trivial case.
What this means, though, is that if you start off with X
and it is bound to a value, then you need to "map" it to the specific gender, Y
, you are now needing to use Y
for that purpose (the "specific" gender).
% Code using X (more general value but specifically bound)
whatgender(X, Y),
% Code using X for more general, but Y for the specific gender
Per my initial comment, you absolutely cannot do this:
% Code using X (more general value but specifically bound)
whatgender(X), % "assign" a new value to X
% THIS IS NOT POSSIBLE
Upvotes: 3