我已经尝试了很多东西,但我找不到如何在 prolog 中实现以下愿望。
if list is empty
call foo function
else
do nothing
我做了什么:
list = [] -> foo(...)
;
fail.
但是,它不起作用
我已经尝试了很多东西,但我找不到如何在 prolog 中实现以下愿望。
if list is empty
call foo function
else
do nothing
我做了什么:
list = [] -> foo(...)
;
fail.
但是,它不起作用
fail
并不意味着“什么都不做”,而是“失败(和回溯)”。
您需要true
改用:
( List == [] -> foo(...) ; true ),
此外,List
应该是一个变量,所以使用大写。
Another, perhaps more idiomatic, way to write this would be
% foo_if_empty(?List) call foo if list is empty
foo_if_empty([]) :- !,foo(...).
foo_if_empty(_).
What my code does is to unify with the first clause if list is empty.
If so, we do a cut. If foo fails, we don't want mypred to succeed. So we don't want to do the second clause. The cut eliminates that possiblity.
Now, if we don't unify with the first clause we'll certainly unify with the second. And it does nothing.
This is a much more idiomatic way of doing if/then/else in Prolog than using ->. -> is usually just used for situations where introducing another pred would obscure rather than enlighten the code, similar to the ?: operator in curly brace languages.