Recursively iterating an array using higher order function