What is "!" in Prolog

LauraW picture LauraW · Jan 9, 2016 · Viewed 7.9k times · Source

Could somebody explain me what does "!" do in Prolog ? I don't understand it. Here I have a code that counts how many sublists of a heterogeneous list have mountain aspect.

nrSubliste([], 0).
nrSubliste([H|T], R):-
    is_list(H),
    munteMain(H),!,
    nrSubliste(T, R1),
    R is R1 + 1.
nrSubliste([_|T], R):-
    nrSubliste(T, R).

munteMain verifies if a linear list has a mountain aspect.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Jan 9, 2016

Exclamation point ! denotes Cut in Prolog, a special goal that always succeeds, and blocks backtracking for all branches above it that may have alternatives.

In your case it means that once a solution to munteMain/1 has been found, the program will never backtrack and look for an alternative solution. Specifically, Prolog will never consider the third clause of your nrSubliste/2 rule, i.e. the one ignoring list head with _, if H in the second clause is such that munteMain(H) succeeds.

Note that using ! makes your code is somewhat harder to read and maintain, because the logic in the third clause depends on the logic of the second clause. You can rewrite your program without a cut using the not provable operator \+:

nrSubliste([H|T], R):-
    is_list(H),
    munteMain(H),
    nrSubliste(T, R1),
    R is R1 + 1.

nrSubliste([H|T], R):-
    is_list(H),
    \+ munteMain(H),
    nrSubliste(T, R).