简体   繁体   中英

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!

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 AB , 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). \nkeys([], []). \n
  • I think the best way is using maplist from library( apply ), and a very simple predicate:

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

    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

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].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM