user1812457
user1812457

Reputation:

Select elements from a list according to indices

Is there a way to define a predicate that behaves (more or less) like this:

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

but without an explicit loop, and without a lambda? I have the feeling that it should be possible to do it with maplist maybe, or findall, but I couldn't figure it out...

(It is of course only true for a List that is a list, Indices that are integers [0, list_length), and all Nths members of List)

On the other hand, this is a very short and obvious definition....

Upvotes: 2

Views: 229

Answers (1)

Fred Foo
Fred Foo

Reputation: 363707

A simple findall/3 suffices:

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

maplist can also do this, but it needs an auxiliary predicate:

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

Upvotes: 1

Related Questions