purescript-st icon indicating copy to clipboard operation
purescript-st copied to clipboard

Inline optimization with `run` still makes calls to `modify`

Open milesfrain opened this issue 4 years ago • 1 comments

Originally reported here.

There's an unexpected call to Control_Monad_ST_Internal.modify in the JS output of the following function:

simulate :: Number -> Number -> Int -> Number
simulate x0 v0 time =
  run do
    ref <- new { x: x0, v: v0 }
    for 0 (time * 1000) \_ ->
      modify
        ( \o ->
            { v: o.v - 9.81 * 0.001
            , x: o.x + o.v * 0.001
            }
        )
        ref
    final <- read ref
    pure final.x
var ref = { value: { x: x0, v: v0 } };                
 
Control_Monad_ST_Internal["for"](0)(time * 1000 | 0)(function (v) {                
  return Control_Monad_ST_Internal.modify(function (o) {                  
    return {                    
      v: o.v - 9.81 * 1.0e-3,                      
      x: o.x + o.v * 1.0e-3                      
    };                    
  })(ref);                  
})();

The original version of the book shows a more optimized JS output that does not make a call to modify:

var ref = { x: x0, v: v0 };     
                                  
Control_Monad_Eff.forE(0)(time * 1000 | 0)(function (i) {    
  return function __do() {    
    ref = (function (o) {    
      return {                                                                         
        v: o.v - 9.81 * 1.0e-3,                                               
        x: o.x + o.v * 1.0e-3    
      };    
    })(ref);    
    return Prelude.unit;    
  };    
})();    
                                       
return ref.x;

milesfrain avatar Apr 25 '20 20:04 milesfrain