根据索引从列表中选择元素

时间:2013-05-28 19:26:28

标签: list prolog

有没有办法定义一个行为(或多或少)的谓词:

% nths(?Indices, ?List, ?Nths)
nths([], _, []).
nths([N|Ns], List, [E|Es]) :-
    nth0(N, List, E),
    nths(Ns, List, Es).

但没有显式循环,没有lambda?我觉得应该可以使用maplistfindall进行此操作,但我无法理解......

(当然只有 List 是一个列表, Indices 是整数[0,list_length]和所有 Nths List 的成员)

另一方面,这是一个非常简短明确的定义......

1 个答案:

答案 0 :(得分:1)

一个简单的findall/3就足够了:

nths(Ns, List, Es) :-
    findall(E, (member(N, Ns), nth0(N, List, E)), Es).

maplist也可以这样做,但它需要一个辅助谓词:

nth0r(L, N, X) :- nth0(N, L, X).
nths(Ns, List, Es) :-
    maplist(nth0r(List), Ns, Es).
相关问题