Prolog 如果输入了特定单词,则附加到列表

Prolog 如果输入了特定单词,则附加到列表,prolog,append,Prolog,Append,我试图将一个列表和一个单词附加在一起,如果用户键入一个特定的单词,我想在列表中添加一个特定的字母 例如,我想根据代词更改列表中输入的单词 ?- append([t,a,l,k], she, X). X = [t, a, l, k, s]. 因此,如果用户输入[t,a,l,k]和she,Prolog将在列表末尾添加's' 到目前为止,我的代码只能附加两个输入的值,而不是基于用户是否输入某个单词 append( [], X, X).

我试图将一个列表和一个单词附加在一起,如果用户键入一个特定的单词,我想在列表中添加一个特定的字母

例如,我想根据代词更改列表中输入的单词

?- append([t,a,l,k], she, X).
X = [t, a, l, k, s].
因此,如果用户输入[t,a,l,k]和she,Prolog将在列表末尾添加's'

到目前为止,我的代码只能附加两个输入的值,而不是基于用户是否输入某个单词

append( [], X, X).                                   
append( [A | B], C, [A | D]) :- append( B, C, D).

result:
?- append([t,a,l,k], she, X).
X = [t, a, l, k|she].
如果他们输入she prolog将“s”而不是“she”添加到列表中,我如何才能做到这一点


谢谢。

您必须首先将原子
she
分解为单个字符

最好使用
my_append/3
,因为
append/3
已经存在

my_append( [], W, [F]) :- atom_chars(W,[F|_]).
my_append( [A | B], W, [A | D]) :- my_append(B, W, D).

:- begin_tests(shemanator).

test("append 'she'", true(X == [t, a, l, k, s])) :-
   my_append([t,a,l,k], she, X).

test("append 'she' to an empty list", true(X == [s])) :-
   my_append([], she, X).

test("append 's'", true(X == [t, a, l, k, s])) :-
   my_append([t,a,l,k], s, X).
   
:- end_tests(shemanator).
诸如此类

?- run_tests.
% PL-Unit: shemanator ... done
% All 3 tests passed
true.

谢谢你,但我真的不明白为什么它会起作用。。。我是prolog的新手,在my_append中没有提到她或她的名字,但不知怎么的,它知道如何在s.@Pone中添加她的变化。因为一个人调用
my_append([A | B],W[A | D])
,而
W
绑定到
she
,这会导致更多调用
my_append([A | B],W[A | D])
,而
W
总是绑定到
she她
(沿着递归),最终导致调用
my_append([],W[F])
W
仍然绑定到
she
,这导致
she
通过'atom_chars(W,[F |)]]分解为其字符。`这导致
F
绑定到[
s
h
e
]中的
s
。然后我们就结束了,因为查询成功了,
[F]
实际上是调用方的
D
,它是调用链上
[A | D]
的一部分,因此我们得到了结果。它是变量的绑定和树的建立,树的叶子上有值(即术语)(但不是计算)。