Prolog读取与键对应的键和打印值

时间:2015-10-18 13:17:05

标签: prolog repeat

我必须实现一个Prolog程序,它接受像[[1,a],[2,b],[1,c]]这样的List,并在循环中请求一个Key。如果用户输入1 [a,c]应该打印,并且应该要求用户输入下一个键,直到用户进入“退出”。

我目前的计划:

%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',
  !.

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

此致 海波

1 个答案:

答案 0 :(得分:1)

这个程序使用故障驱动的循环,你以目标启动程序。然后提示您?-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.

使用repeat的不同版本:

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