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