refactoring the recursive function so that the code is more concise.