23

谁能告诉我如何访问序言中列表的特定成员?例如,我需要访问传递给规则的列表的第三个或第四个元素?

4

4 回答 4

31

nth0(Ind, Lst, Elem)或者nth1(Ind, Lst, Elem)使用 SWI-Prolog,nth0第一个元素的索引为 0。

例如,

nth0(3, [a, b, c, d, e], Elem). %Binds d to Elem
nth1(3, [a, b, c, d, e], Elem). %Binds c to Elem

nth0(Ind, [a, b, c, d, e], d).  %Binds 3 to Ind
nth0(3, [a, b, c, X, e], d).    %Binds d to X

nth0(3, [a, b, c, d, e], c).    %Fails.
于 2012-10-17T17:06:47.410 回答
6

当您需要访问的索引非常小时,您可以使用模式匹配。假设我们需要第三个元素或第四个元素:

third([_,_,E|_], E).
fourth([_,_,_,E|_], E).

如果使用“内联”,这可能会更有用,当列表包含具有位置相关性的信息时。例如

your_rule([_,_,E|Rest], Accum, Result) :-
   Sum is Accum + E,
   your_rule(Rest, Sum, Result).
...
于 2012-10-17T20:44:19.250 回答
1

序言列表是经典列表。访问不是直接的。你必须迭代才能找到你需要的东西。

您可以通过以下方式获取第 n 个元素:

foo( [X1,X2,X3,X4,...,XN|Xs] ) :- ...

其中 [code]X[/code] n是列表的第 n 个元素。对于大于一个小值的n是不切实际的。这大致类似于 C/C++ 指针表达式:

LLNode *nthElement = root->next->...->next ;

否则,您必须使用内置谓词或自制谓词遍历列表以找到所需的元素,例如:

foo(Xs) :- nth_element(Xs,9,X) , ...

nth_element(Xs,N,X) :- nth_element(Xs,0,N,X) 。

nth_element([X|Xs],N,N,X) :- !. nth_element([_|Xs],T,N,X) :- T1 是 T+1 ,nth_element(Xs,T1,N,X)。

于 2012-10-17T17:30:42.137 回答
0

使用funcSWI-Prolog 的库,可以以更简洁的方式编写列表推导:

:- use_module(library(func)).

nth0((Index, List), Result) :-
    nth0(Index,List,Result).

现在,您可以访问列表的两个元素并将它们添加在一起,如下所示:

example :-
    List = [1,5,12,9],
    Y is (nth0 $ (0, List)) + (nth0 $(3,List)), %add the 1st and 4th elements of this list
    writeln(Y). %prints 10
于 2016-09-15T05:51:34.810 回答