2016-12-10 34 views
0
can_go(Place) :- here(X), connect(X, Place). 
can_go(Place) :- ('You cannnot get there from here'), nl, 
fail. 
can_go(location(treasure,room)) :- location(key,in_hand). 
can_go(location(treasure,room)) :- write('cannot enter here without keys'), nl, 
fail. 
+0

它不是完全清楚你想要什么。你能用伪代码来表达你的“if else”问题吗? –

回答

0

这里涉及两个截然不同的概念:是否可以亲自从一个地方到另一个地方搞定,无论你是允许获得从一个地方到另一个地方。一般来说,对于不同的概念你应该有不同的谓词。物理可达性部分由您connect/2谓语为蓝本,但让我们把它更加明确:

reachable(Place) :- 
    here(X), 
    connect(X, Place). 

然后,让你的定义的另一部分重命名为allowed_to_go/1

allowed_to_go(location(treasure,room)) :- 
    location(key,in_hand). 
allowed_to_go(location(treasure,room)) :- 
    write('cannot enter here without keys'), nl, 
    fail. 

现在,你可以如果那个地方是可以到的,去一些地方,你可以去那里。连词(“和”)简直是逗号(,):

can_go(Place) :- 
    reachable(Place), 
    allowed_to_go(Place). 
can_go(Place) :- 
    write('You cannnot get there from here'), nl, 
    fail. 

剩下的一个问题是,如果一个地方到达,但你不能去那里,你将打印两个错误信息,一个其中无关紧要。有几种方法可以解决这个问题。有些人可能会建议添加一个剪辑(!),但如果有更简单,更清晰的选择,则应该避免这种情况。在这个特殊情况下,否定可能是最简单的可能性。

can_go(Place) :- 
    \+ reachable(Place), 
    write('You cannnot get there from here'), nl, 
    fail. 

另一种方法是使用IF-THEN-ELSE运营商(->):如果添加了一个后卫的can_go/1的第二句话,你不会得到虚假错误。 (注:我没有测试任何这一点。)