Prolog,带条件子句的建筑清单 [英] Prolog, building list with conditional clauses

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

问题描述

我需要使用prolog(SWI-flavor)完成这项作业,并且无法理解某些事情。

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

例如,如果我想迭代一个列表并将其元素添加到另一个列表中,但只有当它们满足某些条件时,我该如何处理它?我可以将它们全部添加,或者不添加,但如果我添加检查此条件的子句,则整个递归结果为false。我理解为什么会这样,但不知道如何解决它。基本上我想要的是:

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)当整个目标变为假时不会发生......

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天全站免登陆