Prolog disjunction

你说的曾经没有我的故事 提交于 2020-01-05 03:05:02

问题


Consider this Prolog predicate:

silly:-
    1 = 1.
silly:-
    1 = 2.

When querying, the output answer has two states: true and then false. Is there anyway to ask Prolog to terminate as soon as it hits a true statement in a disjunction?


回答1:


add a cut

silly:-
    1 = 1, !.
silly:-
    1 = 2.

or use if/then/else, but then the 'program' take a very different shape, being the alternative branches merged into a single clause. Also note that, as stated in documentation

Unlike !/0, the choice point of the predicate as a whole (due to multiple clauses) is not destroyed.

silly:-
    ( 1 = 1 -> true ; false ).



回答2:


The question is "Is there anyway to ask Prolog to terminate as soon as it hits a true statement in a disjunction"?

The answer is "Use once/1 when querying for the answer".

For example:

     ?- [user] .
     silly:-
     1=1 .
     silly:-
     1=2 .
     silly:-
     2=2 .
     end_of_file .

     ?- %% query WITHOUT once {results in 2 answers} : %%
     silly .
     true ;
     true.

     ?- %% query WITH once {results in 1 answer} : %%
     once(silly) .
     true.

The use of cut ! does not meet the semantic requirements of the question as stated.

Using cut would be appropriate if the question had been more like "Is there anyway to ask tell Prolog to terminate as soon as it hits a true statement** a statement specially indicated* in a disjunction" ?



来源:https://stackoverflow.com/questions/25346189/prolog-disjunction

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