问题
Given that functional programming is best when sticking to immutable variables as much as possible, and that Ramda always makes shallow copies, how are objects that must be mutable dealt with in a mostly-purely functional framework?
For example, consider PIXI.Sprite (in pixi.js). The display system has an inherent hierarchy that is linked together and has its own way of tracking objects so it can re-use textures, etc. Garbage collecting them could be a real problem.
What sort of approaches can be taken to deal with this (alongside a robust frp system like sodium-typescript)?
Specifically, can this approach be improved:
Having some sort of unsafePerformIO() function that will modify the heavy objects. All modification of those objects is only done through that function.
Lightweight meta-information objects carry all the logic around.
Those lightweight information objects reference the heavy objects directly
Here is a full code sample in Typescript to demonstrate it in action (just need to import PIXI and Ramda). The key lines are in gameLoop():
let app = new PIXI.Application(window.innerWidth, window.innerHeight);
document.body.appendChild(app.view);
let ball = new PIXI.Graphics();
ball.beginFill(0xFF0000);
ball.drawCircle(0,0,40);
ball.endFill();
ball.y = app.stage.height/2;
app.stage.addChild(ball); //app
let ticker = new PIXI.ticker.Ticker();
ticker.add(gameLoop);
ticker.start();
let ballReference = {
ptr: ball,
x: 0
}
function performUnsafeIO(reference) {
reference.ptr.x = reference.x;
}
function gameLoop(deltaTime:number) {
//this version breaks!
//ball = R.assoc('x', ball.position.x + deltaTime * 1, ball);
//This works fine... but are there any gotchas?
ballReference = R.assoc('x', ballReference.x + deltaTime * 1, ballReference);
performUnsafeIO(ballReference);
}
(note, this conversation found via Google is a good reference point: https://web.archive.org/web/20100410001213/http://itmmetelko.com/blog/2008/02/23/functional-programming-immutable-objects-explained-irc-style/)
来源:https://stackoverflow.com/questions/44573496/approach-to-modifying-mutable-objects