3

I want to create a prolog program so that it can search for the minimum number in a list and when the user asks for more solutions (using the ; symbol) the program returns the next minimum number. If the user asks for another solution it returns the next number and so on. I've created the minimum predicate but can't make it to backtrack to get more results, please help.

Thanks in advance.

P.S I am using Swi-prolog

false
  • 10,264
  • 13
  • 101
  • 209
Chadoblie
  • 31
  • 2

2 Answers2

2

We define list_nextmin_gt/3 based on list_minnum/2, tfilter/3 and dif/3:

list_nextmin_gt(Zs0, M, Zs) :-
   list_minnum(Zs0, M0),
   tfilter(dif(M0), Zs0, Zs1),
   (  M0 = M, 
      Zs = Zs1
   ;  list_nextmin_gt(Zs1, M, Zs)
   ).

Sample query:

?- list_nextmin_gt([3,2,1,2,3], M, Rest).
(  M = 1, Rest = [3,2,2,3]
;  M = 2, Rest = [3,3]
;  M = 3, Rest = []
;  false
).

Or, if you don't care about the remaining list items, simply write:

?- list_nextmin_gt([3,2,1,2,3], M, _).
(  M = 1
;  M = 2
;  M = 3
;  false
).
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166
  • @false. or should the "(" ")." go, too? – repeat Dec 09 '15 at 15:39
  • 1
    Too. It does not help: The arity is not mentioned that way. So you need an extra reference mentioning the predicate indicator. – false Dec 09 '15 at 15:46
  • @false. The arity of `(;)/2`? I wonder how `a ; b ; false` is any different from `(a ; b ; c)`...... How about `:- M=1 ; M=2 ; M=3 ; false.` as an answer? – repeat Dec 09 '15 at 17:50
0

Utterly simple solution: Sort the list and return each member of this list:

min(List, Min) :-
    sort(List, Sorted),
    member(Min, Sorted).