1

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

m09
  • 7,490
  • 3
  • 31
  • 58
user1428237
  • 49
  • 1
  • 6

2 Answers2

3

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.

twinterer
  • 2,416
  • 1
  • 15
  • 13
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.

Anniepoo
  • 2,152
  • 17
  • 17
  • 1
    OTOH using `(!)/0` the right way (ensuring steadfastness) is harder than using if-then-else right! – repeat May 04 '15 at 06:55