Change value in Prolog

2020-04-21 04:41发布

问题:

I am new to Prolog, and I want to change the value of a variable, which is extracted from a list. Initially, the variable is n, then on some occasions I would like to change it to a. But using (is)/2 won't work because it only operates on numbers.

Is there an easy way to do this? Suppose my code looks something like this:

change([H|T]) :- set H to a,change(T).
change([]).

Notice H has already been set to n, so the goal H = a fails because n and a cannot be unified.

回答1:

You're hitting the key issue when learning prolog that it doesn't work like procedural languages.

A variable in prolog is a variable in the sense that it can have any value, but at any point in a computation if the variable has been unified then it cannot change unless prolog backtracks.

So, you cannot simply take a list, such as [m, n, o, p] and change it to be [m, a, o, p]. You have to construct a new list.

Here's how:

replace_n_with_a([], []).
replace_n_with_a([n|X], [a|Y]) :- replace_n_with_a(X, Y).
replace_n_with_a([H|X], [H|Y]) :- H \= n, replace_n_with_a(X, Y).

These three predicates take a list and build a new one, but swap n for a whenever it finds it. The original list hasn't changed, but I now have a new one that I can pass to the next part of my code.

To run the above code you may have this:

?- replace_n_with_a([m, n, o, p], Xs), write(Xs), nl.

I get this result:

[m, a, o, p]
Yes.


标签: prolog