I have a list of pairs: [{1, a}, {2, b}, {3, c}, {4, d}]
How can I extract the second element of each pair and make that a separate list?
So: [a,b,c,d]
Sorry, I am new to Prolog, and had a look around for the answer, but could not find it.
您显示的不是对列表。这是:
[1-a, 2-b, 3-c, 4-d].
使用此列表,您可以:
?- pairs_values([1-a, 2-b, 3-c, 4-d], V).
V = [a, b, c, d].
?- pairs_keys([1-a, 2-b, 3-c, 4-d], K).
K = [1, 2, 3, 4].
并且明确的谓词是:
seconds([], []).
seconds([_A-B|Pairs], [B|Secs]) :-
seconds(Pairs, Secs).
如果你坚持,当然:
secs([], []).
secs([{_A, B}|Pairs], [B|Secs]) :-
secs(Pairs, Secs).
但是您可以自己决定什么最有效,请记住:
?- write_canonical({1,a}).
{}(','(1,a))
true.
?- write_canonical(1-a).
-(1,a)
true.
Prolog 上的好材料,除其他外:
仅使用 SWI-Prolog,您可以
:- use_module(library(lambda)).
extract_second(In, Out) :-
maplist(\X^Y^(X = {_,Y}), In, Out).
你可以在那里获得库(lambda):http ://www.swi-prolog.org/download/pack/lambda-1.0.0.tgz