Reputation: 3
How can I repeatedly extract minimum number until the list is empty?
I want to find a minimum number, then exclude it from the original list, then find a minimum again and again, until the list becomes empty.
Input:
?- Find_Minimum([2, 1, 4, 3, 5], C)
Output:
C = 1
C = 2
C = 3
C = 4
C = 5
False
Upvotes: 0
Views: 44
Reputation: 60014
I would had written - more or less - the same answer as @damianodamiano (+1), but tried nevertheless to code something more 'direct' than sorting. It turns out the outcome is rather technical...
:- module(minext, [minext/2,minext/3]).
minext(L,M) :-
minext(L,T,R),
( M=T
; minext(R,M)
).
minext(L,X,R) :-
select(X,L,R),
\+((
member(Y,R),
Y<X
)), !.
Upvotes: 0
Reputation: 2662
Here a simple solution using sort/2
(in SWI):
minimum(L,E):-
sort(L,LSorted),
pick(LSorted,E).
pick([H|_],H).
pick([_|T],E):-
pick(T,E).
?- minimum([2,1,4,3,5],E).
E = 1
E = 2
E = 3
E = 4
E = 5
false
Keep in mind that sort/2
removes duplicates. If you want to keep them use for instance msort/2
(in SWI). For an even simpler solution you can use member/2
:
minimum(L,E):-
sort(L,LSorted),
member(E,LSorted).
?- minimum([2,1,4,3,5],E).
E = 1
E = 2
E = 3
E = 4
E = 5
Upvotes: 1