n00*_*ist 7 conditional if-statement prolog
我需要使用prolog(SWI-flavor)完成这项作业,并且无法解决一些问题.
例如,如果我想遍历一个列表并将其元素添加到另一个列表中,但只有当它们满足某些条件时,我该如何处理它?我可以将它们全部添加,或者不添加,但如果我添加检查此条件的子句,则整个递归结果为"false".我理解为什么会这样,但不知道如何解决它.基本上我想要的是:
goal(Stuff) :- do_something(X),
only_do_this_if_something(Y),
always_do_this(Z).
Run Code Online (Sandbox Code Playgroud)
目前,如果only_do_this_if_something(Y)失败,也always_do_this(Z)不会因为整个目标变错而发生......
Tha*_*dis 10
你可以使用if结构:
<condition> -> (do_something) ; (do_something else)
Run Code Online (Sandbox Code Playgroud)
在这种情况下:
goal(Stuff):-
do_something(X),
if_something(Y)-> do_this(Y) ; true,
always_do_this(Z).
Run Code Online (Sandbox Code Playgroud)
或者你只是写两个条款,如:
goal(Stuff):-
do_something(X),
conditional_stuff(Y),
always_do_this(Z).
conditional_stuff(Y):-
condition(Y),
do_this(Y).
conditional_stuff(_).
Run Code Online (Sandbox Code Playgroud)