Lift free variables out of `loop`
Use same data representation as Java version