F# and C#: The cross-over syntax

As part of my F# presentation to the TRINUG code camp, I did Question #1 of Project Euler.  I started with a typical way a C# programmer might approach it: using mutable variables and looping.  Something like this:

  1. public static Int32 TryOne()
  2. {
  3.     List<Int32> selectedNumbers = new List<int>();
  4.     for (int number = 0; number < 1000; number++)
  5.     {
  6.         if (number % 3 == 0)
  7.         {
  8.             selectedNumbers.Add(number);
  9.         }
  10.  
  11.         if (number % 5 == 0)
  12.         {
  13.             if (!selectedNumbers.Contains(number))
  14.             {
  15.                 selectedNumbers.Add(number);
  16.             }
  17.         }
  18.     }
  19.  
  20.     Int32 total = 0;
  21.     foreach (Int32 number in selectedNumbers)
  22.     {
  23.         total += number;
  24.     }
  25.  
  26.     return total;
  27. }

 

I then demonstrated they way a typical F# might approach the problem:

  1. open System
  2. let tryOne = [1..1000]
  3.                     |> Seq.filter(fun number -> (number%3 = 0 || number%5 = 0))
  4.                     |> Seq.sum

 

There are some differences worth noting.  The first is the terseness of F# and less “noise” of curley-braces and semi-colons.  The second is that the F# is more readable than the C# – assuming the person reading the code is not steeped in the java/C++/C# syntax.  Finally, there are less chance for bugs in the F# code.  In the C# code, there is a chance that selectedNumbers varaible might be altered and the total variable might be altered – esp. when doing the program in a multi-threaded manner.

Next, a more advanced C# developer might use Linq or Lambdas to write the answer like this:

  1. public static Int32 TryTwo()
  2. {
  3.     var total = Enumerable.Range(0, 1000)
  4.                         .Where(number => (number % 3 == 0) || (number % 5 == 0))
  5.                         .Sum();
  6.     return total;
  7. }

 

The similarity between this C# code and the F# code is striking.  The biggest difference is that the OO syntax makes the functions a part of the object being acted upon while the functional syntax makes the functions a part of a separate construct.  This change in perspective is the only real difference – and I am noticing that the more you look at code via the functional way, more mental doors are opened when solving a problem…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: