Brianjs
Brianjs

Reputation: 2339

Find the Keys in a Prolog Pairs List

I currently have a list of (Key,Value) pairs and I want to pull out all the keys to use in another function.

Such that I have a list called

PairsList 

and I want to

retractall(map(Key,_).

I have tried:

retractall(map(PairsList[(Key,_)],_).

but that just throws a syntax error.

Any help would be super!

Upvotes: 2

Views: 1594

Answers (2)

CapelliC
CapelliC

Reputation: 60034

retractall it's a powerful Prolog memory tool, useful for dynamic information managing, but it's important not to abuse of it. In your question, seems irrelevant. If you have a list of pairs (Key,Value) then

  • if you can use SWI-Prolog, there is this interesting library(pairs). Instead of (A,B) uses A-B, but for the representation change you gain much. With that library, the builtin you would use is pairs_keys(Pairs, Keys)

  • without any library, the function (but it's a relation, not a function) is really easy to write in pure Prolog.

    keys([(Key,_)|Pairs], [Key|Keys]) :- keys(Pairs, Keys).
    keys([], []).
    
  • I think the best way is using maplist from library(apply), and a very simple predicate:

    keys(Pairs, Keys) :- maplist(key, Pairs, Keys).
    key((K, _), K).
    

    note that this way we can reuse the logic abstracting from 'actual' pair representation: just add

    key(K - _, K).
    to handle the preferred Prolog way

Upvotes: 2

joel76
joel76

Reputation: 5645

If you use SWI-Prolog and module(lambda), you can write

maplist(\X^Y^(X = (Y,_)), L, L1),

For example this code :

:- use_module(library(lambda)).


t(L, L1) :-
    maplist(\X^Y^(X = (Y,_)), L, L1).

gives

?- t([(1,a), (2,b), (3,c)], L).
L = [1,2,3].

Upvotes: 1

Related Questions