[英]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. retractall它是一个强大的Prolog记忆工具,对动态信息管理很有用,但重要的是不要滥用它。 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 ). 如果你可以使用SWI-Prolog,那就有这个有趣的库( 对 )。 Instead of
(A,B)
uses AB
, but for the representation change you gain much. 而不是
(A,B)
使用AB
,但是对于表示改变,你获得了很多。 With that library, the builtin you would use is pairs_keys (Pairs, Keys) 使用该库,您将使用的内置是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. 没有任何库,函数(但它是一个关系, 而不是一个函数)真的很容易用纯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: 我认为最好的方法是使用库中的maplist( apply ),以及一个非常简单的谓词:
keys(Pairs, Keys) :- maplist(key, Pairs, Keys).键(对,键): - 地图列表(键,对,键)。\nkey((K, _), K).
键((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键(K - _,K)。
If you use SWI-Prolog and module(lambda), you can write 如果你使用SWI-Prolog和模块(lambda),你可以写
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].
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.