Prolog读取键并打印键对应的值

Prolog read keys and print values corresponding to the key

我必须实现一个 Prolog 程序,它接受像 [[1,a],[2,b],[1,c]] 这样的列表并在循环中请求一个键。如果用户输入 1 [a,c] 应该被打印并且应该要求用户输入下一个键直到用户输入 'exit'.

我当前的节目:

%Input: AssocList and Key.
%Output: FindList which contains all Values associated with the Key in AssocList.
as_find(AssocList, Key, FindList) :- 
    as_find(AssocList, Key, Acc, FindList).

as_find([], Key, Acc, Acc).
as_find([], Key, Acc, FindList) :- as_find([], Key, Acc, Acc).
as_find([[Key,D]|R], Key, Acc, FindList) :- my_append(D, Acc, NewFindList), as_find(R, Key, NewFindList, FindList).
as_find([[H,D]|R], Key, List, FindList) :- as_find(R, Key, List, FindList).

%Appends Elem to the given list and returns it in the other list.
my_append(Elem,[],[Elem]).
my_append(Elem,[H|R],[H|Z]) :- my_append(Elem,R,Z).  

%Asks for Keys and writes all Values associated with the keys.
as_search(List) :-
  repeat,
  write('Key?'),
  read(Key),   
  as_find(List, Key, FindList),
  write(FindList),
  Key == 'genug',
  !.

不幸的是,如果我使用 'done' 以外的另一个密钥,程序将以无限循环结束。你能帮忙吗?

此致, 超离子

此程序使用故障驱动循环,您以目标启动程序。 ?-start. 然后系统会提示您添加列表。如果您希望将列表硬编码到程序中而不是作为用户输入,则可以更改此设置。然后我们进入循环,我们给出一个术语,例如 1. 系统将打印列表中的匹配值并循环。如果您输入 stop. 程序终止。

start:-
   format("Enter list:\n",[]),
   read(List),
   enter(List).

enter(List):-
  format("Enter key or stop:\n",[]),
  read(X),
  test(X,List).

test(stop,_):-!.
test(X,List):-
  findall(Y,member([X,Y],List), Values),
  format("~w\n",[Values]),
  enter(List).

如果您输入的键在列表中不存在,将打印一个空列表并带您返回重试。

示例运行:

 ?- start.
 Enter list:
 |: [[1,a],[2,b],[1,c]].
 Enter key or stop:
 |: 1.
 [a,c]
 Enter key or stop:
 |: 2.
 [b]
 Enter key or stop:
 |: stop.

false.

使用重复的不同版本:

start:-
  format("Enter list:\n",[]),
  read(List),
  format("Enter key or stop:\n",[]),
  repeat,
  read(X),
  (   X=stop->!;
    (     findall(Y,member([X,Y],List), Values),
          format("~w\n",[Values]),
          format("Enter key or stop:\n",[])),
          fail).