Prolog,带有条件子句的构建列表 [英] Prolog, building list with conditional clauses

查看:27
本文介绍了Prolog,带有条件子句的构建列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 prolog(SWI 风格)来完成这项家庭作业,并且无法理解某些事情.

I need to do this homework assignment using prolog (SWI-flavor) and cant get my head around some things.

例如,如果我想遍历一个列表并将其元素添加到另一个列表中,但前提是它们满足特定条件,我将如何处理它?我可以将它们全部添加,也可以不添加,但是如果我添加检查此条件的子句,则整个递归结果为假".我明白为什么会这样,但不知道如何解决它.基本上我想要的是:

For example, if i want to iterate through a list and add its elements to another, but ONLY if they meet certain condition, how would I go about it? I can add them all, or none, but if I add clause that checks this condition, the whole recursion turns out as "false". I understand why this is, but have no idea how to fix it. Basically what i want is:

goal(Stuff) :- do_something(X),
               only_do_this_if_something(Y),
               always_do_this(Z).

目前,如果 only_do_this_if_something(Y) 失败,always_do_this(Z) 也不会发生,因为整个目标都变为 false...

Currently, if only_do_this_if_something(Y) fails, also always_do_this(Z) doesnt happen as the whole goal turns false...

推荐答案

可以使用if结构:

<condition> -> (do_something) ; (do_something else)

在这种情况下:

goal(Stuff):-
  do_something(X),
  if_something(Y)-> do_this(Y) ; true,
  always_do_this(Z).

或者您只需编写两个子句,例如:

or you simply write two clauses like:

goal(Stuff):-
  do_something(X),
  conditional_stuff(Y),
  always_do_this(Z).

conditional_stuff(Y):-
  condition(Y),
  do_this(Y).

conditional_stuff(_).

这篇关于Prolog,带有条件子句的构建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆