Prolog Error Errors

I am wondering how to add error checking to Prolog. For example, I have a program that will find how long the list will be:

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

How can I print an error, for example, "The first argument must be a list" when this happens?

+5
source share
1 answer

SWI-Prolog has an 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) 

It is not only difficult to print / use: it is also implementation dependent. Instead, you can (and should) use a library (error) that provides a must_be/2 predicate (unfortunately, it is very difficult to find this on the SWI-Prolog website if you do not 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 means.

+3
source

Source: https://habr.com/ru/post/1235850/


All Articles