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)
当您需要访问的索引非常小时,可以使用模式匹配.假设我们需要第三个元素或第四个元素:
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)
| 归档时间: |
|
| 查看次数: |
31435 次 |
| 最近记录: |