Approach to modifying mutable objects?

旧时模样 提交于 2019-12-11 12:47:15

问题


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:

  1. Having some sort of unsafePerformIO() function that will modify the heavy objects. All modification of those objects is only done through that function.

  2. Lightweight meta-information objects carry all the logic around.

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!