在 Prolog 中更改值 [英] Change value in Prolog
问题描述
我是 Prolog 的新手,我想更改从列表中提取的变量的值.最初,变量是 n
,然后在某些情况下我想将其更改为 a
.但是使用 (is)/2
是行不通的,因为它只对数字进行操作.
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([]).
注意 H
已经设置为 n
,所以目标 H = a
失败,因为 n
和a
不能统一.
Notice H
has already been set to n
, so the goal H = a
fails because n
and a
cannot be unified.
推荐答案
您在学习 prolog 时遇到了一个关键问题,即它不像过程语言那样工作.
You're hitting the key issue when learning prolog that it doesn't work like procedural languages.
prolog 中的变量是一个变量,它可以具有任何值,但在计算中的任何时候,如果变量已经统一,那么除非 prolog 回溯,否则它不能改变.
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.
所以,你不能简单地取一个列表,例如 [m, n, o, p]
并将其更改为 [m, a, o, p]
.您必须构建一个新列表.
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.
方法如下:
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).
这三个谓词获取一个列表并构建一个新列表,但只要找到它就将 n
替换为 a
.原始列表没有改变,但我现在有了一个新列表,可以将其传递给我的代码的下一部分.
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.
我得到这个结果:
[m, a, o, p]
Yes.
这篇关于在 Prolog 中更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!