Extract function for infering element type in for loops