《归来》 Prolog 中谓词的列表
resolve(K, K, _) :- writeln('finished'). %goal state
resolve(CurrentState, GoalState, Path) :-
suc(_, CurrentState, NextState, GoalState),
append(Path, [CurrentState], NextPath),
resolve(NextState, GoalState, NewPath).
我目前有这个算法,它可以正常工作。我像这样运行它:
resolve(0, 10, Path).
我确信算法正在按其应有的方式运行,它会达到目标状态,尽管 Path
的值
Path = []
不是应该发生的情况。路径应包含我的算法已通过的“状态”序列。 可能是什么问题?
resolve(K, K, _) :- writeln('finished'). %goal state
resolve(CurrentState, GoalState, Path) :-
suc(_, CurrentState, NextState, GoalState),
append(Path, [CurrentState], NextPath),
resolve(NextState, GoalState, NewPath).
I currently have this algorithm, and it works as it should. I am running it like this:
resolve(0, 10, Path).
I know for sure that the algorithm is running as it should, it gets to the goal state, although Path
's value is
Path = []
which is not what should happen. Path should contain the sequence of "states" in which my algorithm has passed.
What might be the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 DCG 表示法来描述列表是最简单的:
您也可以手动完成:
这里不需要累加器来获取线性时间。
It's easiest to use DCG notation to describe the list:
You can also do it manually:
There is no need for accumulators here to get linear time.
我相信您构建路径的方式存在问题。
您可能想要重写它,以便将其构建在谓词的头部。
像这样的事情:
第一个子句结束递归:要从状态 K 转到状态 K,您返回 [] 作为路径,因为您已经处于目标状态。
第二个子句构建路径,它获取下一个状态并递归调用resolve,在递归完成时构建您遍历的路径。
I believe there is a problem in the way you want to build the Path.
You might want to rewrite it so as to build it in the head of your predicate.
Something like this:
The first clause ends the recursion: to go from state K to state K you return [] as the Path as you are already in the Goal state.
The second clause builds the path, it gets the next state and calls recursively resolve, building the Path you have traversed when the recursion finishes.
append
谓词中的术语NextPath
应该是NewPath
吗?目前
NextPath
没有任何其他用途,因此Path
必须绑定到[]
,因为NextPath
能够完全绑定到[CurrentState]
。Should the term
NextPath
in yourappend
predicate beNewPath
?Currently there isn't any other usage of
NextPath
soPath
must be binding to[]
becauseNextPath
is able to bind fully to[CurrentState]
.