reduce right recursion to reduce stack overhead