2016-12-10 37 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的第二句話,你不會得到虛假錯誤。 (注:我沒有測試任何這一點。)