0

I have got some values H, and I would like to find the maximum one using \+, how can i do it?

maxValue(X) :-
  Get(Id, X),
  \+( Get(Id, Y), X < Y ).

don't have a clue....please help, thanks!

Kaarel
  • 10,554
  • 4
  • 56
  • 78
Tom
  • 19
  • 2
  • 2
  • 3
  • Please place a backslash before the backslash so that it becomes visible as a backslash. Only needed when not marked as code. –  Mar 15 '11 at 21:07
  • 1
    possible duplicate of [Max out of values defined by prolog clauses](http://stackoverflow.com/questions/1701693/max-out-of-values-defined-by-prolog-clauses) – Fred Foo Mar 16 '11 at 11:33

2 Answers2

3

Using negation is one way to find the maximum. And it really works. Here is an example:

   p(2).  
   p(1).  
   p(3).  

   ?- p(X), \+ (p(Y), Y > X).  
   X = 3

But the complexity will be O(n*n) where n is the number of facts. But the maximum can be determined in O(n). So maybe the following is more efficient for large fact bases:

   :- dynamic(the_max/1).  
   update_max(X) :-  
      the_max(Y), X>Y, !, retract(the_max(Y)), assertz(the_max(X)).  
   update_max(_).  

   find_max(X) :-  
      assertz(the_max(0)),  
      (p(Y), update_max(Y), fail; true),  
      retract(the_max(X)).  

   ?- find_max(X).  
   X = 3

But watch out, when you use it from multiple threads, you need to adapt it a little, i.e. make the_max thread local.

Best Regards

1

See also these questions/answers:

Community
  • 1
  • 1
Kaarel
  • 10,554
  • 4
  • 56
  • 78