将声明性DSL转换为嵌套函数调用

问题描述 投票:4回答:1

我有一个python库,可根据nested function calls构建特殊的迭代器(行为树)。尽管该API具有相当不错的轻量级语法(由于它是python),但它实际上可以使用声明性DSL。

这是我所设想的粗略草图:

DSL(使用YAML):

tree:
  - sequence:
    - do_action1
    - do_action2
    - select:
      - do_action3
      - sequence:
        - do_action4
        - do_action5
      - do_action6

将导致以下嵌套函数调用:

visit(
    sequence(
        do_action1(),
        do_action2(),
        select(
            do_action3(),
            sequence(
                do_action4(),
                do_action5(),
                ),
            do_action6(),
            )
        )
    )

我无法确切地看到如何执行此操作。因为DSL必须表示一棵树,所以简单的深度优先遍历似乎是合适的。但是,为了构建嵌套的函数调用,我必须以某种方式将其内翻。它可能包含一些巧妙的中间堆栈之类的东西,但是我不太了解。什么是执行此转换的正确方法?

python parsing dsl behavior-tree
1个回答
3
投票

[我认为您可以让python跟踪函数调用和参数,而不是自己通过堆栈来完成。

假设您有一个YAML解析树,其中的每个节点代表一个函数调用,并且此节点的每个子节点都是一个参数(它也是一个函数调用,因此它可能具有自己的参数)。

然后定义函数evaluate,该函数将如下评估该树的节点(伪代码:]:

def evaluate(node):
    # evaluate parameters of the call
    params = []
    for child in node:
        params.append(evaluate(child))

    # now make the call to whatever function this node represents,
    # passing the parameters
    return node.function.call(*params)

最后,调用evaluate并将YAML树的根作为参数,您应该获得所需的行为。


略有不同的评估应用结构

def evaluate(node):
    # evaluate parameters of the call
    params = [ evaluate(child) for child in node ]

    # apply whatever function this node represents
    return node.function.call(*params)
© www.soinside.com 2019 - 2024. All rights reserved.