Transitive closure function