prolog小案例二

这是保存到文件的代码如下:

room(kitchen).
room(office).
room(hall). 
room('dining room').
room(cellar). 

door(office, hall).
door(kitchen, office).
door(hall, 'dining room').
door(kitchen, cellar).
door('dining room', kitchen).

location(desk, office).
location(apple, kitchen). 
location(flashlight, desk). 
location('washing machine', cellar).
location(nani, 'washing machine').
location(broccoli, kitchen).
location(crackers, kitchen).
location(computer, office).

edible(apple).
edible(crackers).
tastes_yucky(broccoli).
here(kitchen). 

现在打开编辑器GNU-Prolog,打开文件可以直接询问机器:

房间里面有什么,通过;号隔开,我们可以看到机器会根据上面逻辑告诉你有什么。

| ?- room(X).

X = kitchen ? ;

X = office ? ;

X = hall ? ;

X = 'dining room' ? ;

X = cellar

(31 ms) yes
| ?- 
接下来:在房间里面并且可以吃的有什么?

| ?- location(X,kitchen),edible(X).

X = apple ? ;

X = crackers ? ;

no

逻辑告诉我们有:apple、crackers、no表示没有了。


现在输入trace.竟如debug模式,输入notrace退出。


| ?- trace.
The debugger will first creep -- showing everything (trace)

(15 ms) yes
{trace}
| ?- notrace.
The debugger is switched off

yes

在debug模式下输入上面语句我们可以看到,调试会有四个端口:Call、Fail、Redo、Exit。

{trace}
| ?- location(X,kitchen),edible(X).
      1    1  Call: location(_42,kitchen) ? 
      1    1  Exit: location(apple,kitchen) ? 
      2    1  Call: edible(apple) ? 
      2    1  Exit: edible(apple) ? 

X = apple ? ;
      1    1  Redo: location(apple,kitchen) ? 
      1    1  Exit: location(broccoli,kitchen) ? 
      2    1  Call: edible(broccoli) ? 
      2    1  Fail: edible(broccoli) ? 
      1    1  Redo: location(broccoli,kitchen) ? 
      1    1  Exit: location(crackers,kitchen) ? 
      2    1  Call: edible(crackers) ? 
      2    1  Exit: edible(crackers) ? 

X = crackers ? ;
      1    1  Redo: location(crackers,kitchen) ? 
      1    1  Fail: location(_42,kitchen) ? 

(31 ms) no




你可能感兴趣的:(Prolog)