本文介绍了Prolog 中的简单 nth1 谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 SWI Prolog 中,有一个谓词可以在名为 nth1 的列表中找到第 n 个项目.我想实现我自己的谓词版本,但是如果您查看列表 (nth1) 代码,SWI 会非常复杂.有没有更简单的方法?

With SWI Prolog, there's a predicate that finds the nth item in a list called nth1. I want to implement my own version of the predicate but SWI's is so complicated if you look at the listing(nth1) code. Is there a simpler way of doing it?

谢谢:)

推荐答案

SWI 代码有点复杂,因为谓词可用于从变量索引生成:

The SWI code is a bit complex because the predicate can be used to generate from a variable index:

?- nth1(Idx,[a,b,c],X).
Idx = 1,
X = a ;
Idx = 2,
X = b ;
Idx = 3,
X = c ;
false.

如果你不想要这种行为,nth1/3 可以很容易地用 nth0 实现:

If you don't want that behavior, nth1/3 can be implemented easily in terms of nth0:

nth1(Idx,List,X) :-
    Idx0 is Idx-1,
    nth0(Idx0,List,X).

编辑:也可以不用nth0,只需几行代码:

Edit: it's also possible to do without nth0 in just a few lines of code:

nth1(1,[X|_],X) :- !.
nth1(Idx,[_|List],X) :-
    Idx > 1,
    Idx1 is Idx-1,
    nth1(Idx1,List,X).

这篇关于Prolog 中的简单 nth1 谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 16:30