Search code examples
error-handlingprologtry-catchiso-prologprolog-toplevel

Prolog - How do I catch an error of incorrect arity?


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.

Solution

  • 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.