Prolog,访问列表的特定成员?

Dav*_*ter 18 list prolog unification

任何人都可以告诉我如何访问prolog列表中的特定成员?比方说,我需要访问传递给规则的列表的第3或第4个元素?

joe*_*l76 26

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.
Run Code Online (Sandbox Code Playgroud)

  • 以下是使用例子? - L = [a,b,c],nth0(Ind,L,a),nth0(2,L,X).L = [a,b,c],Ind = 0,X = c.或? - L = [a,b,c],nth1(Ind,L,a),nth1(2,L,X).L = [a,b,c],Ind = 1,X = b. (2认同)

Cap*_*liC 7

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

third([_,_,E|_], E).
fourth([_,_,_,E|_], E).
Run Code Online (Sandbox Code Playgroud)

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

your_rule([_,_,E|Rest], Accum, Result) :-
   Sum is Accum + E,
   your_rule(Rest, Sum, Result).
...
Run Code Online (Sandbox Code Playgroud)