Prolog:一次对列表的一个元素求和



我是Prolog的新手,并决定尝试解决一个问题,其中我有一个符号序列,每个符号的值为1或-1。我需要的是将它们全部相加,一次一个元素,并提取第一次总和降至 0 以下的索引。由于我来自命令式背景,所以我正在想象一个计数变量和一个 for 循环,但显然我不能在 Prolog 中做到这一点。

value('(', 1).
value(')', -1).
main(R) :- readFile("input", R), ???
readFile(Path, R) :- 
open(Path, read, File), 
read_string(File, _, Str), 
stringToCharList(Str, Xs), 
maplist(value, Xs, R).
stringToCharList(String, Characters) :-
name(String, Xs),
maplist(toChar, Xs, Characters ).
toChar(X, Y) :- name(Y, [X]).

如您所见,到目前为止,我真正管理的所有内容都是读取包含序列的文件,并将其转换为 1 和 -1。我不知道该何去何从。我想问题有三个方面:

  • 我需要遍历列表
  • 我需要对列表中的每个元素求和
  • 我需要返回某个索引

有什么建议吗?我可以以某种方式切断迭代会将总和降至零以下的列表,然后返回长度吗?

我将在Prolog中使用辅助变量的原理来充当计数器,直到条件达到我们想要的。然后,辅助计数器在基本情况下的该点与变量统一。

我在这里盲目地假设您的代码按所述工作。我没有测试它(这取决于你)。

main(IndexAtZeroSum) :- readFile("input", R), index_at_zero_sum(R, IndexAtZeroSum).
readFile(Path, R) :- 
open(Path, read, File), 
read_string(File, _, Str), 
stringToCharList(Str, Xs), 
maplist(value, Xs, R).
stringToCharList(String, Characters) :-
name(String, Xs),
maplist(toChar, Xs, Characters ).
toChar(X, Y) :- name(Y, [X]).
% The following predicate assumes indexing starting at 0
index_at_zero_sum([V|Vs], IndexAtZeroSum) :-
index_at_zero_sum(Vs, V, 0, IndexAtZeroSum).
% When sum is zero, Index is what we want
index_at_zero_sum(_, 0, Index, Index).
index_at_zero_sum([V|Vs], Sum, CurIndex, Index) :-
S is Sum + V,
NextIndex is CurIndex + 1,
index_at_zero_sum(Vs, S, NextIndex, Index).

index_at_zero_sum/2为总和变为零的给定列表提供索引。它通过使用辅助谓词index_at_zero_sum/4来实现,从第一个值的总和(总和是值本身)开始,当前索引从 0 开始。因此,第二个参数是索引 0 处的总和。后续调用index_at_zero_sum/4增量索引并累积总和,直到总和变为 0。此时,基本情况成功,并将第 4 个参数与当前索引统一起来。如果在列表变为空之前总和从未变为 0,则谓词将失败。


您还可以通过使用get_char/2来避免读取整个文件和创建数字列表:
index_at_zero_sum(Path, Index) :-
open(Path, read, File),
get_char(File, C),
value(C, V),
(   index_at_zero_sum(File, V, 0, Index)
->  close(File)
;   close(File),
fail
).
index_at_zero_sum(_, 0, Index, Index).
index_at_zero_sum(File, Sum, CurIndex, Index) :-
get_char(File, C),
value(C, V),
S is Sum + V,
NewIndex is CurIndex + 1,
index_at_zero_sum(File, S, NewIndex, Index). 

最新更新