有几种方法可以包含“键值”。一种是将键值对与连字符函子一起使用。我将steal大量借鉴 CapelliC 对基本问题的出色回答,并添加关键的制表逻辑:
% Key not present, then it goes in with count 1
place_key(Key, [], [Key-1]).
% Key is at the head, then it's included in the new list with incremented count
% and the rest of the list is unchanged
place_key(Key, [Key-V|Rest], [Key-V1|Rest]) :-
V1 is V+1.
% Current head is not the key, so it's just copied over and the rest
% of the list is processed
place_key(Key, [K-V|Rest], [K-V|List2]) :-
Key \= K,
place_key(Key, Rest, List2).
所以,例如:
| ?- place_key(x, [], L).
L = [x-1] ? ;
no
| ?- place_key(x, [x-2,y-3,z-1], L).
L = [x-3,y-3,z-1] ? ;
no
| ?- place_key(w,[x-2,y-3,z-1], L).
L = [x-2,y-3,z-1,w-1] ? ;
no
键值格式的一个很好的方面是 ISO Prolog 定义了一个谓词 keysort/2 来识别它。
| ?- place_key(q,[x-2,y-3,z-1], L), keysort(L, LX).
L = [x-2,y-3,z-1,q-1]
LX = [q-1,x-2,y-3,z-1] ? ; % List sorted by key
no
| ?-
您也可以使用两个元素的子列表 ([Key,Value]) 来执行此操作,这可能是最初的意图,尽管尚不清楚。如果需要,上述逻辑很容易适应这种格式。 (在任何有K-V 模式的地方,都用[K,V] 替换它。)如果你对这样的列表进行列表排序,它仍然会按键排序:
| ?- sort([[c,1],[x,4],[d,5],[a,6],[m,2]], L).
L = [[a,6],[c,1],[d,5],[m,2],[x,4]]
yes
| ?-