获取列表中指定索引处的元素

Get an element in a list at a specified index

我需要编写一个程序,使用指定的索引 return 列表中的一个元素。

我们有一个英文字母列表 X = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]

从 0 开始,我必须 return,例如索引为 13 的数字,所以字母 'n',你如何 return 列表中的元素指定索引?

这是我的工作,但仍然没有 运行 正确。

position(0, 0, [], a).
position(X, I, [H1|T1], _):-
    position(X, I1, T1, H1),
    I = I1 + 1.

这只是遍历列表并边走边数的问题。尝试这样的事情:

select( [X|_]  , 0 , X ) .
select( [_,Xs] , N , C ) :- N > 0 , N1 is N-1, select(Xs,N1,C).

select( Xs , N , C ) :- select(Xs,0,N,C) .

select( [X|_]  , N , N , X ) .
select( [_|Xs] , V , N , C ) :- V1 is V+1, select(Xs,V1,N,C).

后者将以更 Prolog-like 的方式工作,bi-directionally。它不关心你是否指定了索引:

  • select( [a,b,c,d] , N , C ) 先后成功
    • N=0, C=a
    • N=1, C=b
    • N=2, C=c
    • N=3, C=d
  • select( [a,b,c,d] , 2 , C ) 成功了
    • C=c
  • select( [a,b,c,d] , N , d ) 成功了
    • N=3

我的做法也是“往下数数,到零时从前面开始匹配”:

:- use_module(library(clpfd)).

position(0, [Elem|_], Elem).
position(Pos, [_|T], Elem) :-
    Pos #= Pos_ + 1,
    position(Pos_, T, Elem).

您的请求“一个程序 return 列表中的一个元素,使用指定的索引”是一个命令式请求,就像您可能在 Python;采用单个索引并 returning 单个元素。更改为 Prolog 关系思维方式会让您看到 Nicholas Carey 的评论:

will work bi-directionally. It doesn't care if you specified an index or not

所以你可以给出一个元素并得到一个索引。除此之外,他们还可以检查元素是否在索引处;这确认 'dog' 在位置 3,并且说 'cow' 不在位置 3:

?- position(3, [apple,box,cat,dog], dog).
true

?- position(3, [apple,box,cat,dog], cow).
false

在回溯时,找到一个元素的所有位置,这会在两个地方找到'box':

?- position(Pos, [apple,box,cat,dog,box], box).
Pos = 1 ;
Pos = 4

这意味着与 Python 相比,此代码与 x = items[i]i = items.index(x) 以及 enumerate(items)items[i] == x 重叠。