What is "!" in Prolog
Asked Answered
E

1

11

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.

Exclamatory answered 9/1, 2016 at 12:48 Comment(1)
Also check out the canonical answer on when to use !/0 in Prolog.Buddy
U
4

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).
Udo answered 9/1, 2016 at 12:54 Comment(1)
Ok, I think I understood it and thank you a lot for the alternative of using operator \+.Exclamatory

© 2022 - 2024 — McMap. All rights reserved.