我如何在prolog中找到最小的值

时间:2016-02-04 17:44:19

标签: prolog

我有以下代码

option(2):-
    write('Enter place of origin: '), read(Origin),
    write('Enter place of destination: '), read(Destination),
    path(Origin, Destination, Path, Length),nl,nl,
    printPath(Path), write(' '),
    writef(' TOTAL DISTANCE = %d', [Length]),nl,fail;true.

我想找到长度中最小的值。我得到类似于此

的输出
bahirdar-->mota  TOTAL DISTANCE = 100
bahirdar-->markos-->mota  TOTAL DISTANCE = 70

1 个答案:

答案 0 :(得分:1)

如果要查找数据库中任意两个位置之间的最小距离(根据谓词路径/ 4),使用CappelliC建议的aggregate库将起作用。如果要查找用户输入程序的最短路径,则需要存储该信息。一个简单的方法是asserta用户的答案:

:- dynamic user_path/2.

option(2):-
  write('Enter place of origin: '), read(Origin),
  write('Enter place of destination: '), read(Destination),
  path(Origin, Destination, Path, Length),
  asserta(user_path(Origin, Destination)),
  nl,nl,     
  printPath(Path), write(' '),
  writef(' TOTAL DISTANCE = %d', [Length]),nl,fail
 ;
  true.

然后你可以找到

的最小路径
min_path(Path) :- 
 aggregate(
           min(L,Path), 
           Origin^Destination^Path^(
            user_path(Origin, Destination),
            path(Origin, Destination, Path, L)
           ), 
           Length
          ).