Functional alternatives to references

Started by
1 comment, last by klems 15 years, 3 months ago
Hi, I'm thinking of writing a simple game in Haskell. However, since my imperative habits go pretty deep, I'm having a hard time figuring some things out. Imagine a simple tower defense game that has a homing missile launcher. In it, the data structure representing an enemy that the homing missile has locked on to and is moving on the screen should be in several places: the live enemies list, the moving enemies list (as opposed to offscreen enemies,) and the homing missile's target. In an imperative language, I'd just use references. Obviously, this isn't possible in a functional language. How would I go about doing this in Haskell? I've thought of simply giving every enemy an ID and store that instead of references, or perhaps store its place/index in the big heap of enemies, but I don't know if that's the 'correct' solution, or if there is a better way of doing things. Anyone with a know-how of functional languages who can point me in the right direction here?
Advertisement
Well, you have to store a reference (because, in practice, the missile references its target). You cannot use an explicit reference, because explicit references are immutable (they're part of the language), but you can use an implicit reference (by means of an index, handle or key) so that the missile references "whatever can be found in container X at key Y". Changing container X then automagically updates the missile reference.

If you look under "indexing" in this article, you can find an example of such an associative system based on an array.
I see. I'll go with the indexing approach then. Thanks!

This topic is closed to new replies.

Advertisement