我知道如何在 Prolog 中找到特定元素的索引,但是有没有办法找到大于 X
的数字的第一个实例的索引.例如,假设我有一个包含所有数字的列表,但列表中某处的随机数大于 1。我怎样才能找到大于 1
的数字的第一个实例的索引?我对 Prolog 真的很陌生,并且不太擅长谓词的子目标。
最佳答案
你想写一个列表、索引和值之间的关系。我们称之为 list_1stindex_gt/3。最好使用第四个参数来跟踪当前索引。但是,最好不要用这个累加器打扰用户,因此您可以使用辅助谓词和当前索引的附加参数,我们称之为 list_1stindex_gt_/4。假设您想开始计算 1
处的索引。 (否则将第四个参数更改为 0
)您可以像这样定义 list_1stindex_gt/3 :
:-use_module(library(clpfd)).
list_1stindex_gt(L,I,GT) :-
list_1stindex_gt_(L,I,GT,1).
对于 list_1stindex_gt_/4 你有两种情况:
1
并在列表尾部继续搜索。 你可以在 Prolog 中这样写:
list_1stindex_gt_([X|Xs],I,GT,I) :- % case 1
X #> GT.
list_1stindex_gt_([X|Xs],I,GT,Acc0) :- % case 2
X #=< GT,
Acc1 #= Acc0+1,
list_1stindex_gt_(Xs,I,GT,Acc1).
示例查询:给定列表中第一个大于 1 的元素位于哪个索引?
?- list_1stindex_gt([1,1,1,1,5,1,1,2],I,1).
I = 5 ? ;
no
大于 1 的第一个元素可以在三个变量的列表中的哪个索引处?
?- list_1stindex_gt([A,B,C],I,1).
I = 1,
A in 2..sup ? ;
I = 2,
A in inf..1,
B in 2..sup ? ;
I = 3,
A in inf..1,
B in inf..1,
C in 2..sup ? ;
no
大于变量
X
的第一个元素可以在哪个索引处在三个变量的列表中? ?- list_1stindex_gt([A,B,C],I,X).
I = 1,
X#=<A+ -1 ? ;
I = 2,
X#>=A,
X#=<B+ -1 ? ;
I = 3,
X#>=A,
X#=<C+ -1,
X#>=B ? ;
no
此外,您可以考虑@mat 对 this answer 的建议改进回答您之前提出的问题:遵循 (#<)/3 背后的想法您可以定义 (#>)/3 然后使用 if_/3 定义 list_1stindex_gt_/4像这样:
:-use_module(library(clpfd)).
#>(X, Y, T) :-
zcompare(C, X, Y),
greater_true(C, T).
greater_true(<, false).
greater_true(>, true).
greater_true(=, false).
list_1stindex_gt(L,I,GT) :-
list_1stindex_gt_(L,I,GT,1).
list_1stindex_gt_([X|Xs],I,GT,Acc0) :-
if_(X #> GT,
(I #= Acc0),
(Acc1 #= Acc0+1, list_1stindex_gt_(Xs,I,GT,Acc1))).
这样第一个查询就成功了,而不会留下不必要的选择点:
?- list_1stindex_gt([1,1,1,1,5,1,1,2],I,1).
I = 5.
关于list - 大于 X 的第一个元素的索引(Prolog),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38283683/