extract a loop as a function