Prolog101(11)

使用Prolog时,有时需要人为的终止回溯,此时会用到谓词cut,使用符号!来表示。

data(one).  
data(two). 
data(three).

cut_test_a(X) :- data(X).
cut_test_a('last clause').

cut_test_b(X) :- data(X), !.  
cut_test_b('last clause').

cut_test_c(X,Y) :- data(X), !, data(Y).
cut_test_c('last clause'). 

来测试一下

1- cut_test_a(X), write(X), nl, fail. 
one
two
three
last clause
false.

2- cut_test_b(X), write(X), nl, fail. 
one
false.

3- cut_test_c(X,Y), write(X-Y), nl, fail.
one-one
one-two
one-three
false.

此外,可以用not谓词判断条件是否成立

not(X) :- call(X), !, fail. 
not(X)

下面两种方式是等效的:

have(apple).

eat():-
write('yummy...').

eat_fruit_a(X):- 
have(X), 
!,
eat().

eat_fruit_b(X):-  not(can_not_eat(X)),eat().
can_not_eat(X):-  
not(have(X)).

eat_fruit_c(X):-  can_eat(X),eat().
can_eat(X):- have(X).
can_eat(X):- fail.
1- eat_fruit_a(apple).
yummy...
true.

2- eat_fruit_a(pear).
false.

3- eat_fruit_b(apple).
yummy...
true.

4- eat_fruit_b(pear).
false.

5- eat_fruit_c(apple).
yummy...
true .

6- eat_fruit_c(pear).
false.

Comments are closed.