1

我已经尝试了很多东西,但我找不到如何在 prolog 中实现以下愿望。

if list is empty
        call foo function
else
        do nothing

我做了什么:

list = [] -> foo(...) 
             ;
             fail.

但是,它不起作用

4

2 回答 2

3

fail并不意味着“什么都不做”,而是“失败(和回溯)”。

您需要true改用:

( List == [] -> foo(...) ; true ),

此外,List应该是一个变量,所以使用大写。

于 2012-06-04T08:08:27.537 回答
0

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.

于 2012-06-05T16:45:35.647 回答