添加到列表(如果尚未在列表中),更改列表中的元素(PROLOG)

时间:2014-03-14 00:30:47

标签: list prolog append

我是Prolog的新手,我正在尝试编写一个函数来检查给定的密钥是否在列表中;如果是,它将增加列表中的值,否则它将附加到列表的末尾。到目前为止,这是我的代码。

placeKey( Key, []       , List2 ) :- append(Key,[], List2).  %base case: append to empty list
placeKey( Key, [K|Rest] , List2 ) :-  %If front entry isnt the one we want then continue on the rest
  Key \= K ,
  put( Key ,Rest,List2).
placeKey(Key,[Key|Rest], List2):- %how to update item value?

但是,当项目不在给定列表中时,这只返回一个列表,我甚至不知道如何解决实际更改列表中项目的问题。任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:2)

我会使用模式匹配而不是'命令'来解决任务:

placeKey(Key, [], [Key]).
placeKey(Key, [K|Rest], [K|List2]) :- Key \= K, placeKey(Key, Rest, List2).
...

答案 1 :(得分:1)

有几种方法可以包含"键值"。一种是使用带连字符仿函数的键值对。我将窃取大量借用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
| ?-

答案 2 :(得分:0)

这样的东西?

这使用Key/Count形式的元组来表示每个列表项。

add_or_increment( Dict , K , Updated ) :-     % to add or increment a tuple in a dictionary-like list
  nonvar(K) ,                                 % - the key must be bound.
  append( Prefix , [K/N|Suffix] , Dict ) ,    % - use the key to find the tuple in the list.
  ! ,                                         % - eliminate the choice point.
  M is N+1 ,                                  % - increment the count
  append( Prefix , [K/M|Suffix] , Updated )   % - construct the updated list
  .                                           % - Easy!
add_or_increment( Dict , K , [K/1|Dict] ) :-  % otherwise, just prepend the key to the source list to create the updated list
  nonvar(K)                                   % - assuming, of course, that the key is bound.
  .                                           % - Even easier!