使用函数编程语言处理具有内部状态的外部库的最优雅的方法是什么?
我目前正在尝试 Scala 开发,但我需要与 box2d 等库集成来处理物理。问题是这需要依赖于管理其自身状态的外部库。您可以跟踪进入 box2d 世界的物体。总结一下游戏中的各个方面:
- Box2d 管理世界中的状态并在每个刻度/步骤后修改它们
- 您创建(使用 FP)传递到这个世界的物体
- Box2d 在内部修改这些物体的状态
- 以跟踪您保留对它们的引用的对象
- 您很可能希望使用主体中的信息来呈现代码,因此我假设跟踪该信息的唯一方法是跟踪可变集合中的所有引用。它需要在所有帧中生存。
所以我的问题是:
如何以一种优雅的方式(对于函数式编程)跟踪这些引用,以及如何最大限度地减少它对其余代码的纯度的影响?
诸如状态之类的东西我猜单子不会在这里帮助我
I'm currently playing around with Scala development, but I need to integrate with libraries such as box2d to handle physics. The problem is that this requires to depend on an external library which manages its own state. You keep track of the bodies which you pass into the box2d world. To sum up the aspects in play:
- Box2d manages the state in the world and modifies them after each tick/step
- You create (using FP) the bodies which are passed into this world
- Box2d modifies the state of these bodies internally
- To keep track of the objects you keep a reference to them around
- You will most likely want to use the information in the bodies to render your code, so I would assume the only way to keep track of that information is to keep track of all references in a mutable collection. It needs to survive all frames.
So my question is:
How can you keep track of those references in an elegant way (for functional programming) and how can you minimize the effect it has on purity in the rest of your code?
Stuff like state monads are not going to help me here I guess
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最实用的方法是确定必须保持哪些不变量才能封装不纯的操作,而不会泄露存在副作用的事实,然后,一旦有证据表明情况如此,就将状态隐藏在其中“unsafePerformIO”的。
另一种方法是通过例如显式的“我已初始化”令牌来公开存在内部状态的事实,该令牌是不可伪造的且不可分割的,以保证对底层资源的线性访问。
The most practical way is to determine what invariants must hold for the impure actions to be encapsulated without leaking the fact there are side effects, and then, once you have evidence that is the case, hiding the state inside of a "unsafePerformIO".
An alternative is to expose the fact there is internal state, by e.g. an explicit 'i have been initialized' token, that is unforgeable, and unsplittable, to guarantee linear access to the underlying resource.
函数响应式编程是一个活跃的研究领域,尽管您可能可以使用如果您不需要对因果关系进行建模,请在此处Reader Monad。
Functional Reactive Programming is an active area of research, although you may be able to use the Reader Monad here if you don't need to model causality.