我正在 Ivan Bratko 书中学习 Prolog DCG 语法 * 和 ** 解析树:“人工智能编程”
我发现以下示例存在一些困难,该示例提供了一种 DCG 语法,该语法从属于已定义语言的字符串创建解析树。
定义的语言是机械臂的移动列表,只能有两种类型:向上和向下,因此[up,up,down,up,up]属于我的 DCG 语法定义的语言。
该程序还提供了一个meaning/2谓词,它解释与某个字符串关联的解析树,这意味着机器人手臂穿过的距离(而它与向上移动相关联,值+1,值-1与移动相关联下)
因此,例如对于列表[up,up,down,up,up],mean/2谓词计算 +3 距离
这是我的示例代码(运行良好):
move(move(Step)) --> step(Step).
move(move(Step, Move)) --> step(Step), move(Move).
step(step(up)) --> [up].
step(step(down)) --> [down].
/* Take the parse tree of a string that belong to the language defined by the DCC grammar and
calculate the total distance whereas that an up move give a +1 distance and a down move
give -1 distance
*/
meaning(move(Step, Move), Dist):-
/* Calculate the distance given by the current step node
(which can be +1 or -1) */
meaning(Step, D1),
/* Calculate the distance given by the current moove node
(which must be calculated recursively on a subtree having
a moove node as root */
meaning(Move, D2),
/* The final distance series of moves is the distance of the
current step + the distance diven from the moves in the
moove subtree */
Dist is (D1 + D2).
meaning(step(Step), Dist):- meaning(Step, Dist).
meaning(move(Step), Dist):- meaning(Step, Dist).
% step(up) means that the distance is +1
meaning(step(up), 1).
% step(down) means that the distance is -1
meaning(step(down), -1).
所以我有一个mean/2谓词,它采用解析树并计算移动的总距离。
因此,我有 2 个基本案例来表示与单个移动(到一步)相关的距离值,对于向上的步骤可以是 +1,对于向下的步骤可以是 -1:
meaning(step(up), 1).
meaning(step(down), -1).
含义/2采用一个解析树,根据 DCG 语法的定义,它有一个移动节点作为根:这个根将有一个左子节点,它是一个步进节点(所以它是单步移动,所以它有一个特定的距离+1 或 -1 关联)和作为移动节点的右子节点(因此它表示另一个子树)
所以总距离是当前步骤的距离之和,即+1或-1(当前移动根的左子节点)+右子树中的距离。
我认为这是正确的,这对我来说很清楚
我不明白的是代码中这两个谓词对我来说代表什么:
meaning(step(Step), Dist):- meaning(Step, Dist).
meaning(move(Step), Dist):- meaning(Step, Dist).
我不能坚持我的推理:-(