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

时间:2020-09-11 13:58:08

标签: prolog append

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

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

?- append([t,a,l,k], she, X).
X = [t, a, l, k, s].

因此,如果用户输入[t,a,l,k]而她是,则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].

我如何做到这一点,如果他们键入她的序言,则会在列表中添加“ s”而不是“ she”?

谢谢。

1 个答案:

答案 0 :(得分:0)

您必须首先将原子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.