views:

254

answers:

2

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

+3  A: 

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.

Apocalisp
+4  A: 

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.

Don Stewart
Hmm I do not totally get your answer, what would be an example of the encapsulated invariants such that the fact there are side effects is not leaked?
Tomh
Any example of `unsafePerformIO` with Scala for those of us that don't know Haskell?
huynhjl