12

How can I check if a predicate exists in a Prolog program? That would be an exists/1, like:

?- exists(some_predicate).
false.

?- assert(some_predicate).
true.

?- exists(some_predicate).
true.
false
  • 10,264
  • 13
  • 101
  • 209
vmassuchetto
  • 1,529
  • 1
  • 20
  • 44

2 Answers2

15

You can use current_predicate/1, current_predicate/2 or predicate_property/2 (for the last you will probably need functor/3):

?- current_predicate(a/1).
false.

?- functor(A,a,1),predicate_property(A,visible).
false.

?- functor(A,a,1),current_predicate(_,A).
false.

?- assert(a(42)).
true.

?- current_predicate(a/1).
true.

?- functor(A,a,1),predicate_property(A,visible).
A = a(_G136).

?- functor(A,a,1),current_predicate(_,A).
A = a(_G122).

current_predicate/2 and predicate_property/2 (with visible) succeeds if the predicate can be autoloaded while currrent_predicate/1 fails

Junuxx
  • 14,011
  • 5
  • 41
  • 71
Thanos Tintinidis
  • 5,828
  • 1
  • 20
  • 31
1

the 'old fashioned way', but accepted in ISO, is clause/2. You could encounter it while reusing/browsing some of the older examples.

example:

?- [user].
|: app([], Y, Y).
|: app([X|Xs], Y, [X|Zs]) :- app(Xs, Y, Zs).
|: % user://1 compiled 0,15 sec, 17 clauses
true.

?- clause(app(X,Y,Z),Body).
X = [],
Y = Z,
Body = true ;
X = [_G338|_G339],
Z = [_G338|_G342],
Body = app(_G339, Y, _G342).
CapelliC
  • 59,646
  • 5
  • 47
  • 90
  • 3
    This is accepted in ISO only for predicates with the public property! By default it does not work for static code. – false Jun 14 '14 at 10:06