F# and C#: The cross-over syntax
October 8, 2013 Leave a comment
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:
- public static Int32 TryOne()
- {
- List<Int32> selectedNumbers = new List<int>();
- for (int number = 0; number < 1000; number++)
- {
- if (number % 3 == 0)
- {
- selectedNumbers.Add(number);
- }
- if (number % 5 == 0)
- {
- if (!selectedNumbers.Contains(number))
- {
- selectedNumbers.Add(number);
- }
- }
- }
- Int32 total = 0;
- foreach (Int32 number in selectedNumbers)
- {
- total += number;
- }
- return total;
- }
I then demonstrated they way a typical F# might approach the problem:
- open System
- let tryOne = [1..1000]
- |> Seq.filter(fun number -> (number%3 = 0 || number%5 = 0))
- |> 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:
- public static Int32 TryTwo()
- {
- var total = Enumerable.Range(0, 1000)
- .Where(number => (number % 3 == 0) || (number % 5 == 0))
- .Sum();
- return total;
- }
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…