def fold()

in fluent/migrate/util.py [0:0]


def fold(fun, node, init):
    """Reduce `node` to a single value using `fun`.

    Apply `fun` against an accumulator and each subnode of `node` (in postorder
    traversal) to reduce it to a single value.
    """

    def fold_(vals, acc):
        if not vals:
            return acc

        head = list(vals)[0]
        tail = list(vals)[1:]

        if isinstance(head, FTL.BaseNode):
            acc = fold(fun, head, acc)
        if isinstance(head, list):
            acc = fold_(head, acc)
        if isinstance(head, dict):
            acc = fold_(head.values(), acc)

        return fold_(tail, fun(acc, head))

    return fold_(vars(node).values(), init)