1:- module(swi_lists, [ zip/3, 2 pairs/2, % ?Items, ?Pairs 3 indexed/2, 4 indexed/3, 5 take_at_most/3, 6 select1/3, % +Indices, +List0, -List 7 select_apply1/3, % +Indices, :Goal, +Extra 8 comb2/2 % ?List1, ?List2 9 ]). 10 11:- meta_predicate select_apply1( , , ).
Only succeeds if the lists and sub-lists have matching lengths.
21zip([], [], []). 22zip([H1|T1], [H2|T2], [[H1, H2]|T]) :- zip(T1, T2, T).
There needs to be an even number of list elements. This requirement proceeds from the definition of pairing; it pairs the entire list including the last. The predicate fails otherwise.
34pairs([], []). 35pairs([H1, H2|T0], [H1-H2|T]) :- pairs(T0, T).
45indexed(Items, Pairs) :- indexed(Items, 1, Pairs). 46 47indexed([], _, []). 48indexed([H|T0], Index0, [Index0-H|T]) :- 49 Index is Index0 + 1, 50 indexed(T0, Index, T).
60take_at_most(0, _, []) :- !. 61take_at_most(_, [], []) :- !. 62take_at_most(N, [H|T0], [H|T]) :- succ(N0, N), take_at_most(N0, T0, T).
75select1(Indices, List0, List) :- maplist(select1_(List0), Indices, List). 76 77select1_(List, Index, Elem) :- nth1(Index, List, Elem).
86select_apply1(Indices, Goal, Extra) :-
87 select1(Indices, Extra, Extra1),
88 apply(Goal, Extra1).
99comb2([H|T0], [H|T]) :- comb2(T0, T). 100comb2([_|T0], [H|T]) :- comb2(T0, [H|T]). 101comb2(_, [])