Writing a safe program

I have this question about writing a prolog program, and maybe this has been answered before, but I havent seen it yet.

Lets say I would want to write a swi-prolog program with very safe performance, would it make it safer if I specify all the allowed var and nonvar situations for all predicates used?

and my second question: If i place all the Cuts as high and as early as possible in the predicates, could this produce performance equally fast as procedural languages?

so that if you Cut out all the backtracking, will it always be fast?

thankyou

What is safe performance? Fast? Predictable?

What does that mean? Spreading var/1 and nonvar/1 calls through the program? That is rarely a good idea. These tests are mostly for meta-reasoning about Prolog predicates. Sometimes they are needed to make multi-moded predicates fast, i.e., test for modes (+,-) and (-,+) and reorder the body accordingly.

Using cuts is a fiercely debated subject. I guess most experts would agree to use them as little as possible and as early as possibly. People mostly disagree what “as little as possible” means, notably how far do you go designing the data structures to reduce the use of cuts and how much useless backtracking you consider tolerable.

If performance is an issue, start by using profile/1 to get insight in what is going on.

1 Like

thankyou for the information.

with safe i mean predictable,

only in some cases the written code will allow for ambiguity concerning instantiation of variables.

then only in those cases you would have to use the var or nonvar check to specify 1 type of behaviour?

I mean if you are not completely sure about the instantiations of variables in your program, you could force yourself to specify var and nonvar checks everywhere, would that be a method to become completely sure about the programs behaviour?

If you expect something to be true and you want to ensure that, use assertion/1, as in

    ...,
    assertion(nonvar(X)),
    ...,

That traps an error in normal mode, but if the code is compiled with optimization enables (-O or set_prolog_flag(optimise, true)), the assertion/1 call is removed. Pretty much like C assert(), but that name was taken to mean something else in Prolog :slight_smile: