how to implement if-then-else in prolog

2019-07-26 05:17发布

问题:

I have tried so many things but I could not found How I can implement following wish in prolog .

if list is empty
        call foo function
else
        do nothing

What I did:

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

But, it does not work

回答1:

fail does not mean "do nothing", but "fail (and backtrack)".

You need to use true instead:

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

Also, List should be a variable, so use upper case.



回答2:

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.



标签: prolog