Find min of list using fail, backtracking Prolog

為{幸葍}努か 提交于 2019-12-11 03:38:04

问题


I want to calculate the minimum of list, using fail which causes to backtrack. How do i change min(Min, X, Min), to make it work.

%min(X, A, B) X is the min of A, B
min(X, X, Y) :- X =< Y.
min(Y, X, Y) :- Y < X.

member(X, [X|_]).
member(X, [_|Ys]) :-
  member(X,Ys).

program :-
  Min is 1000,
  (member(X, [1, 2, 3, 4]),
  writeln(X),
  min(Min, X, Min), %This is wrong !
  fail;
  writeln(Min),
  true).

My previous working code for calculating min

solve([Head|Rest], Ans) :-
   solve(Rest, Till),
   min(Ans, Head, Till). 

But i do not want to do this, as for calling solve, i am doing something like this

program :-
   findall(X, solve(List, X), Z).

which is causing to find all solutions of X and storing in memory. This method is not working for large inputs, getting killed.

Hence, i want to calculate the min of each solve call on fly and not store as did using findall.


回答1:


If you're worried about memory usage, you shouldn't be using a guess-and-check metaphor (which using failure implies you're using). There's an O(n) algorithm that doesn't require failure at all.

minlist(Min, [X|Xs]) :- minlist(X, Xs, Min).

minlist(Min, [], Min).
minlist(MinSoFar, [X|Xs], Min) :-
    min(NextMin, MinSoFar, X),
    minlist(NextMin, Xs, Min).


来源:https://stackoverflow.com/questions/46495963/find-min-of-list-using-fail-backtracking-prolog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!