Tomas Petricek, who interned under the supervision of Don Syme, is publishing.

“Thinking differently about problems" is available for free.
Parallelization of functional programs
Imagine that we’re writing a computer game and we have a list of characters controlled by the computer. In a single step of the game, we want to remove all characters that died since the last step and we want to calculate new state of the game character (such as new location). Also a character can perform some operation with the world (for example picking an item from the world).
Imperative Solution
List<GameCharacter> dead = new List<GameCharacter>(); foreach(GameCharacter ch in Characters) { if (!CharacterIsAlive(ch)) dead.Add(ch); else ch.PerformStep(this.World); } Characters.RemoveAll(dead);
Functional Version
1 Characters = Characters.Filter(CharacterIsAlive); 2 Characters = Characters.Select(PerformStep); 3 this.World = Characters.Aggregate(this.World, ModifyWorld);
- Filter out dead characters
- Calculate new state for each character
- Calculate new state of the world
{ 2 comments… read them below or add one }
Hi
Is this not a more functional style? (Based more on Haskell-style functions):
this.World = Characters.Filter(CharacterIsAlive).Select(PerformStep).Aggregate(this.World, ModifyWorld);
This removes the assignments to the Characters variable.
Regards
Rich
Hi Rich,
you’re right – avoidng mutation (assignments to Characters) is definitely more functional. That’s a very useful comment and I’ll consider it when editing the first chapter!
Sequencing of functions is one thing and avoiding any mutations is the second thing, so it could as well be:
var Characters1 = Characters.Filter(..)
var Characters2 = Characters1.Select(..)
However, when writing some .NET applications, it is quite common to have some mutable state (even though it is usually hidden somewhere). In Haskell, the “main program loop” can be a recursive function, so you don’t need any mutation. Even though it could be (hopefuly) written in .NET as well, the key idea of this example isn’t avoiding mutaton, but writing the code in a more declarative and succinct style.
Anyway, thanks for your comment! It’ll be very useful when doing the next review for the first chapter!