add a general sort-topologically function