how to implement if-then-else in prolog

时间秒杀一切 提交于 2020-01-14 04:24:24

问题


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.



来源:https://stackoverflow.com/questions/10878127/how-to-implement-if-then-else-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!