Search code examples
prologswi-prolog

How to call a goal and bind the number of logical inferences to a variable in Prolog?


According to the manual, time(+Goal) executes Goal and prints, amongst other things, the number of logical inferences used.

How can I bind the number of logical inferences to a variable?


Solution

  • The following code is specific to SWI-Prolog. Currently, many other Prologs do not permit to count the number of inferences, mainly due to many different optimizations that would blur that number.

    :- meta_predicate(call_inferences(0, -)).
    
    call_inferences(Goal_0, Inferences) :-
       statistics(inferences, I0),
       Goal_0,
       statistics(inferences, I1),
       Inferences is I1-I0-1.
    

    Usage:

    ?- call_inferences(true,N).
       N = 1.
    ?- call_inferences(nreverse([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30],L), N).
       L = [30, 29, 28, 27, 26, 25, 24, 23, 22|...], N = 496.