Unroll recursion into loop inside lookup()