Functional Programming
Since around Christmas, I’ve been slowly falling in love with F#. The more I look at it, read about it and try it, the more I appreciate functional programming in general, and particularly F#.
One of the joys is that the list is so core to the entire experience. As I’ve learnt more as a programmer, I’ve realised that so much of what we do is working with lists, and although C# is getting better with things like LINQ, it’s still so far behind.
F# also has the advantage that it’s a .NET language and is not only fully functional, but also fully object oriented. It’s a superset of C#, so you get the joys of C#, along with being able to program functionally.
A few quick examples to demonstrate some F#:
let square x = x * x let sumOfSquares n = [1..n] |> List.map square |> List.sum let sumOfOddSquares n = [1..2..n] |> List.map square |> List.sum printfn "Sum of Squares 1..100: %i" (sumOfSquares 100) printfn "Sum of odd Squares 1..100: %i" (sumOfOddSquares 100)
The equivalent C# code:
public class Program { public static int Square(int x) { return x*x; } public static int SumOfSquares(int n) { int sum = 0; for (int i = 0; i < n; ++i) { sum += Square(i); } return sum; } public static int SumOfOddSquares(int n) { int sum = 0; for (int i = 1; i < n; i+=2) { sum += Square(i); } return sum; } static void Main(string[] args) { Console.WriteLine("Sum of Squares 1..100: {0}", SumOfSquares(100)); Console.WriteLine("Sum of odd Squares 1..100: {0}", SumOfOddSquares(100)); } }
And the C# code using modern techniques like LINQ:
public class Program { public static int Square(int x) { return x*x; } public static int SumOfSquares(int n) { return Enumerable.Range(1, n) .Select(i => Square(i)) .Sum(); } public static int SumOfOddSquares(int n) { return Enumerable.Range(1, n) .Where(i => i % 2 != 0) .Select(i => Square(i)) .Sum(); } static void Main(string[] args) { Console.WriteLine("Sum of Squares 1..100: {0}", SumOfSquares(100)); Console.WriteLine("Sum of odd Squares 1..100: {0}", SumOfOddSquares(100)); } }
The LINQ code is clearly nicer than the old style C# code, but F# is just so much more concise and easier to understand. The benefits of easier comprehension along with the benefits of first-class lists are just fantastic.
Learning about F# is the most I’ve been interested in programming since discovering mobile development so many years ago. It should be very exciting to carry on with F# and see what the future brings.
Leave A Comment