6

I'm wondering how to go about adding error checking in Prolog. For instance I have a program that will find how long a list is:

listlen([],0). 
listlen([_|T],N) :-
   listlen(T,X),
   N is X+1.

How would I print out an error like "The 1st argument has to be a list" when it happens?

repeat
  • 18,496
  • 4
  • 54
  • 166
Asia x3
  • 606
  • 2
  • 16
  • 37
  • In this particular case, there are good reasons to not produce an error. See [this comparison](https://www.complang.tuwien.ac.at/ulrich/iso-prolog/length) for the behavior of various systems in this situation. – false Apr 11 '16 at 10:20

1 Answers1

3

SWI-Prolog has ISO-compliant exception handling, so you can actually throw errors as defined in the standard.

?- throw(error(type_error(list, foo), context(foo/0, 'Must be a list'))).
ERROR: foo/0: Type error: `list' expected, found `foo' (an atom) (Must be a list)

This is not only difficult to type/use: it is also implementation dependent. Instead, you can (and should) use library(error), which provides the must_be/2 predicate (sadly, it is very difficult to find this on the SWI-Prolog website if you don't know what you are looking for):

?- must_be(list, [foo]).
true.

?- must_be(list, foo).
ERROR: Type error: `list' expected, found `foo' (an atom)

I assume that other Prolog implementations that support exception handling provide very similar facilities.

David Tonhofer
  • 14,559
  • 5
  • 55
  • 51
  • 4
    There is another reason why writing `throw(error(E,Imp_def))` is problematic: The second argument of `error/2` is implementation defined. So code that gives an explicit term that is not specific to an ISO conforming implementation may not work. – false Nov 13 '15 at 10:50
  • 2
    @false Yes. Actually, it is quite difficult (because documentation) to figure out the exact "ISO error term definition". –  Nov 13 '15 at 15:18
  • 2
    You know [this](http://www.complang.tuwien.ac.at/ulrich/iso-prolog/error_k#error_classes)? – false Nov 13 '15 at 16:28
  • 2
    @false no I did not. This is a great reference, thank you. –  Nov 13 '15 at 16:42