You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SWI-Prolog中Amzi!冒险教程代码执行异常求助

SWI-Prolog冒险教程look/0谓词修复方案

你遇到的问题核心是Amzi! Prolog和SWI-Prolog在回溯控制上的差异:Amzi!可能允许用false强制回溯输出所有结果,但SWI-Prolog中,若谓词以false结尾,调用该谓词会直接失败,导致后续子目标(比如list_things/1)无法执行。

两种可行的修复写法

方法1:用forall/2遍历输出(推荐)

forall/2会遍历所有满足第一个参数的子句,执行第二个参数的动作,最终返回true,不会中断后续代码。

% 输出当前地点的所有连接
list_connections(Place) :-
    forall(connection(Place, Dest, Dir),
           (write('You can go '), write(Dir), write(' to '), write(Dest), nl)).

% 输出当前地点的所有物品
list_things(Place) :-
    forall(thing(Item, Place),
           (write('There is a '), write(Item), ' here.'), nl)).

% 查看当前环境的look谓词
look :-
    current_place(Current),
    write('You are in '), write(Current), nl,
    list_connections(Current),
    list_things(Current).

方法2:给列表谓词添加成功终止子句

如果想保留fail回溯的写法,需要在谓词末尾加一个无操作的成功子句,让谓词输出完所有内容后返回true:

% 输出所有连接,回溯完后成功
list_connections(Place) :-
    connection(Place, Dest, Dir),
    write('You can go '), write(Dir), write(' to '), write(Dest), nl,
    fail.  % 强制回溯,输出下一个连接
list_connections(_).  % 所有连接输出完后,匹配此子句返回true

% 输出所有物品,回溯完后成功
list_things(Place) :-
    thing(Item, Place),
    write('There is a '), write(Item), ' here.'), nl,
    fail.
list_things(_).

% look谓词正常执行所有子目标
look :-
    current_place(Current),
    write('You are in '), write(Current), nl,
    list_connections(Current),
    list_things(Current).

关键逻辑说明

  • 两种写法的核心都是确保list_connections/1和list_things/1在完成所有输出后,最终返回true,这样look/0才能按顺序执行完所有子目标,不会中途因失败终止。
  • forall/2是SWI-Prolog中更简洁、易读的遍历方式,推荐优先使用。

内容的提问来源于stack exchange,提问作者Brian Dolan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 15:10:41