Real World Functional Programming With examples in F# and C#

by Doug Finke on September 2, 2008

in C#, F#, Functional Programming

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

Book cover

“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);
  1. Filter out dead characters
  2. Calculate new state for each character
  3. Calculate new state of the world

{ 2 comments… read them below or add one }

1 Rich 09.03.08 at 3:37 pm

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

2 Tomas Petricek 09.03.08 at 6:53 pm

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!

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>