开发者

prolog question find maximum using negation operator \+

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

maxValue(X) :-
  G开发者_运维知识库et(Id, X),
  \+( Get(Id, Y), X < Y ).

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


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


See also these questions/answers:

  • Prolog query to find largest element in database?
  • Max out of values defined by prolog clauses
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜