1

Not sure if the question is worded correctly or not, my apologies. Basically what I want to do is create some kind of error handling in Prolog. For example:

fruit(apple, pear).

Now if the user were to query:

 ?- fruit(X).

How would I inform the user they have made an error? and return a message along the lines of:

Data should be entered in the format: 'fruit(X, Y)' Please check your query and 
try again.
false
  • 10,264
  • 13
  • 101
  • 209
fleggle
  • 61
  • 5

2 Answers2

3

In ISO-Prolog and conforming systems, the system signals such an error as an existence_error(procedure,fruit/1). To be more precise, there is a Prolog flag unknown which should be set to error to get that behavior. Most systems take this as (the very reasonable) default. But to be sure, simply issue the goal set_prolog_flag(unknown,error).

Note that the error says that fruit/1 is expected to exist, but does not make any further assumptions as you do.

You are suggesting that the error is a missing argument. That might very well be the error. Equally well, it could be a typo meaning fuit/1 which is French (he flees) or Latin (he was). Or maybe you simply forgot to nest the term appropriately. Who knows. There are many good theories what the actual error might be, so your suggestion should be a bit more cautious.

In many systems there are similar suggestions, they are often connected to the toplevel loops that interprets uncaught errors.

You can catch such errors yourself like so:

?- catch(Goal, error(existence_error(procedure,Inex),_), Action_on_error).
false
  • 10,264
  • 13
  • 101
  • 209
0

I don't think that's an application programmer's job. Some Prolog systems already has this feature.

For this particular case you can just create a predicate with "wrong" arity that outputs a message:

fruit(_) :-
    write('Data should be entered in the format: \'fruit(X, Y)\' Please check your query and try again.'), 
    nl, 
    fail.
Sergii Dymchenko
  • 6,890
  • 1
  • 21
  • 46