CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Matthew Podwysocki

Life of a Functional Programmer

September 2008 - Posts

  • Object Oriented F# - Creating Classes

    In the past couple of posts, I covered extension everything in F#.  This allows me to extend .NET types with such things as extension static and instance methods, properties, properties with indexers, events and so on.  But, let's go back to the beginning and cover object oriented programming with F# from the ground up.  I like to stress that F# is not only a first class functional language, albeit a more impure one than say Haskell, but it also treats imperative and object oriented code as first class citizens as well.  To be able to mix and match for the appropriate programming style makes this a very powerful tool, to be able to use functional aspects with first class citizenship, but as well with imperative and object oriented, well, then the sky is the limit.  With that, let's go over some of the things that make F# a player in this space.

    Let's get caught up to where we are so far:


    Defining Classes

    As I will point out several times, F# is a pretty flexible language.  With this, you will find that there are several ways of defining classes, whether it be explicit constructors, constructors in the type definition among other things.  Constructed classes in F# must follow the sytanx, with those items in the brackets being option, and the ones with the asterisk may appear zero to many times.

    type TypeName optional-arguments [ as ident ] =
      [ inherit type { as base } ]
      [ let-binding | let-rec bindings ] *
      [ do-statement ] *
      [ abstract-binding | member-binding | interface-implementation ] *
     

    From the above syntax, I can specify the inheritance, local functions and values (let syntax), verify parameters with the do syntax and member properties, methods and interface implementations. 

    Defining a simple class is very straightforward.  Consider if I want to implement a person class and override the ToString() to output some meaningful input.  The code for implementing this is compact without a lot of pomp and circumstance such as this.

    type Person = { FirstName:string; LastName:string; Age:int }
      with override x.ToString() =
        sprintf "%s %s is %d years old" x.FirstName x.LastName x.Age
          
    let p1 = { FirstName = "Matthew"; LastName = "Podwysocki"; Age = 31 }
    printfn "%s" (p1.ToString())

    What's nice about this approach is that I can define these simple classes and once they are constructed, they are immutable by default.  Very nice for message construction and other operations.  But, if you want more behaviors inside your defined classes, then it's best to use a more explicit syntax as below.


    Constructing Classes

    Using the construction style, I can create simple value objects such as a Geocoordinate to hold a latitude and longitude as well as have the capability of calculating the distance between two instances of Geocoordinates.

    type Geocoordinate(lat:float, lon:float) =
      
      let PI = System.Math.PI
      
      // Validate arguments
      do if lon > 180.0 || lon < -180.0 then invalid_arg "lon"
      do if lat > 90.0 || lat < -90.0 then invalid_arg "lat"
      
      // Properties
      member x.Latitude with get() = lat
      member x.Longitude with get() = lon
      
      // Methods
      static member private DegreesToRadians(deg) =
        deg * PI / 180.0
      
      static member GetDistance(g1:Geocoordinate, g2:Geocoordinate)
        let x = (sin(Geocoordinate.DegreesToRadians g1.Latitude)
                 sin(Geocoordinate.DegreesToRadians g2.Latitude)
                 cos(Geocoordinate.DegreesToRadians g1.Latitude)
                 cos(Geocoordinate.DegreesToRadians g2.Latitude)
                 cos(abs((Geocoordinate.DegreesToRadians g2.Longitude)
                         (Geocoordinate.DegreesToRadians g1.Longitude))))
        let acos_x = atan(sqrt(1.0 - pown x 2) / x)
        let distance = 1.852 * 60.0 * ((x / PI) * 180.0)
        distance
     

    In the above class, I specified the default constructor to take in a lat and lon.  From there, I can use the do syntax to validate the parameters.  I expose the lat and lon parameters also as Latitude and Longitude member properties.  And then I specified a static instance method that calculates the distance between two instances of Geocoordinate classes.

    Alternatively, I could specify the constructors manually instead of during the initial type definition by using the new keyword to define my constructors as well such as the following.

    type Geocoordinate =
      
      val lat:float
      val lon:float
     
      new(lat:float, lon:float) = { lat = lat; lon = lon; }
        
      // Properties
      member x.Latitude with get() = x.lat
      member x.Longitude with get() = x.lon
      
      // Rest Ommitted

    The first example is the preferred way as you can be more flexible while using the do and let syntax, whereas this above solution does not allow for this.  Instead, I would only focus on this style of constructor for structs only.  But the flexibility here gives you some latitude in terms of your particular coding style.

    Code Reuse Through Modules

    Another particularly powerful feature is the ability for code reuse by importing modules.  For example, had some of those functions been implemented in an external module, then I can easily reuse them by opening them.  In the above example, the DegreesToRadians and GetDistance functions could have been defined externally such as this.

    module GeospatialModule =
      let PI = System.Math.PI
      
      let degrees_to_radians deg =
        deg * PI / 180.0
      
      let calculate_distance lat1 lon1 lat2 lon2 =
        let x = (sin(degrees_to_radians lat1)
                 sin(degrees_to_radians lat2)
                 cos(degrees_to_radians lat1)
                 cos(degrees_to_radians lat2)
                 cos(abs((degrees_to_radians lon2)-
                         (degrees_to_radians lon1))))
        let acos_x = atan(sqrt(1.0 - pown x 2) / x)
        let distance = 1.852 * 60.0 * ((x / PI) * 180.0)
        distance
     

    And then I could implement the class in a much more concise format while using these defined functions.

    open GeospatialModule

    type Geocoordinate(lat:float, lon:float)
      // Validate arguments
      do if lon > 180.0 || lon < -180.0 then invalid_arg "lon" 
      do if lat > 90.0 || lat < -90.0 then invalid_arg "lat"   
      
      // Properties
      member x.Latitude with get() = lat
      member x.Longitude with get() = lon
      
      // Methods
      static member GetDistance(g1:Geocoordinate, g2:Geocoordinate)
        calculate_distance g1.Latitude g1.Longitude
                           g2.Latitude g2.Longitude
     

    The code as written is much more compact than before as I have refactored my code to use functions from modules and cut down on the clutter inside my code.

    Optional and Named Arguments

    In F#, you'll find that the OOP constructs that F# supports are very much oriented towards API designers.  As such, there is a need to permit designers to specify named arguments and allow for the fact that some arguments are optional.  Named arguments are simply when creating an object, specify the name before the assignment operator such as the example below.  Using this style makes reading object initialization much more readable as you are not relying on argument position, instead by given name. 

    let g1 = new Geocoordinate(lat = 12.0, lon = 34.0)

    An optional parameter can be specified during the declaration by prefixing the argument name with a question mark (?).  This becomes translated to an Option<'a> type which allows for either some value or no value at all.  Should the value not be specified, you can set the default argument value through the let syntax.  Let's walk through a simple example of a simple class called TextBoxInfo.

    type TextBoxInfo(?text:string, ?color:Color, ?font:Font) =
      // Initialize
      let text = defaultArg text ""
      let color = match color with
        | None -> Color.Red
        | Some c ->
      let font = match font with
        | None -> new Font(FontFamily.GenericSerif, 10.0f)
        | Some f -> f
        
      // Properties
      member x.Text = text
      member x.Color = color
      member x.Font = font
     

    I specified default values for each should they not have been specified.  This allows me to specify only the arguments I need to do my operation.  Some examples of how to create a TextBoxInfo are below.

    let tb1 = new TextBoxInfo("Hello textbox")
    let tb2 = new TextBoxInfo(text = "Hello textbox"
                              color = Color.Aqua)
    let tb3 = new TextBoxInfo(color = Color.Purple,
                              font = new Font(FontFamily.GenericMonospace, 10.0f))

    This syntax makes my code a bit more concise as I don't have to input default values, and instead only concentrate on the things I actually need.  Named and optional arguments are features that C# has needed desperately for some time, especially in regards to the COM Interop story.


    Wrapping It Up

    This is the first in a series on telling the story of object oriented programming in F#.  As programmers, we can decide which language paradigm fits best for the application and the mix of functional, imperative and object oriented programming is essential in today's environments.  This series is intended on how you can mix and match the paradigms, but more importantly, make you aware of the choices you have.  Next up on the plate, we'll cover interfaces, operators, overloading and so on.

  • DC ALT.NET - Building ASP.NET MVC Apps Wrapup

    I want to thank Troy Goode for his presentation tonight at DC ALT.NET.  He gave a great demo of how to build from scratch an ASP.NET MVC blog engine, which is a lot to ask given our two hour timeframe.  And yet, he pulled it off nicely.  As promised, Troy has posted his materials from the presentation here.

    I'm hoping in the near to set up some workshops in the Washington DC area on such subjects to take a single topic and go deep as we can on it.  I think this would be a pretty valuable experience for a lot of people, and topics like building real-world applications doing TDD with ASP.NET MVC would be high on the list.  Stay tuned to more details.

    Next month, we're going to be covering Kanban and Lean Software Development.  This is a topic that has been on my mind a lot and covered a bit by my CodeBetter compatriots here and here.  Reading "The Toyota Way", the two Lean Software Development books by the Poppendiecks and the Lean Software Development mailing list has me definitely thinking.  Stay tuned to the mailing list for more details.

  • Reminder - DC ALT.NET - 9/24/2008 - Building ASP.NET MVC Applications

    Just a reminder that the September meeting for DC ALT.NET will be on September 24th, 2008 from 7PM-9PM.  Check out our site and our mailing list for more information as it becomes available.  This month, Troy Goode will present on building applications with ASP.NET MVC.  This will be a basic introduction, but also how to build practical applications, such as a blog engine using MVC.  Download the latest bits, ASP.NET MVC Preview 5 and follow along as I will be.

    I'd like to thank Cynergy Systems, Inc for sponsoring this month's event.  As a side note, they are actively looking for experienced .NET developers with interest in WPF and Silverlight.  So, if you're looking for a great company that is a leader in the Rich Internet Applications area and want to work in downtown Washington D.C., definitely check them out. 

    The information is as follows:

    DateTime:
    9/24/2008 - 7PM-9PM

    Location:
    Cynergy Systems Inc.
    1600 K St NW
    Suite 300
    Washington, DC 20006
    Show Map



    Be there and hope to see a passionate crowd!
  • Herding Code Episode 18 - Functional Programming and F#

    A couple of days ago, I had the pleasure of recording Episode 18 of Herding Code on Functional Programming and F#.  The topic on their minds was around functional programming, and more in particular with some of the things I've been doing around the .NET space both C# and F#. 

    Some of the things I talked about in this episode were around the following topics:

    • What is Functional Programming and why should we care?
    • C# and the evolution of the language with functional aspects and where it falls short
    • What is F# and what is the value proposition?
    • Some of the uses of F#

    I had a lot of fun doing this episode and I hope it shows!  Feedback is always appreciated.

  • Functional C# - Pattern Matching

    In the past, I've covered quite a bit of functional programming in C# 3.0 and how you can implement some of the basic constructs using the language.  In preparation for the Richmond Code Camp coming up on October 4th, for which I'm planning to present "Functional C# -or- How I lost the foreach and learned to love LINQ", I'm revisiting some of the topics I've talked about in the past.  One of those topics is pattern matching.


    Pattern Matching

    Earlier in my introduction to F# series, I covered pattern matching and how clear and concise it can make your programs.  You can more program to your intent instead of needing to switch between if statements, case statements and so on.  Basically, pattern matching is the way of checking for conditions on a given parameter with rigid specifications.  Pattern matching is a strongly functional programming concept and is present in F#, OCaml, Haskell, Erlang, etc.  Erlang is an interesting one here as you can define the patterns, which in turn will define the type.  As Erlang is a dynamic language, you do not need to specify the type beforehand, so implementing patterns then define that type.

    Pattern matching in F# is pretty flexible as it allows to match against explicit values, structures, lists, guarded ranges, .NET types, active patterns and so on.  The basic syntax is match ... with ... expressions such as this.

    match expression with
    | pattern_1 -> expression_1
    | pattern_2 -> expression_2
    | pattern_n -> expression_n
     

    Similarly, I could use the function keyword should I create a function with the parameter to pattern match against instead of the above syntax, such as this.

    let get_value = function
      | None -> 0
      | Some n -> n

    let value = get_value (Some 25)

    As you may notice, F# has very flexible syntax for describing these, so let's look at a few more ideas before we move on.


    Data Structure Matching

    We can pattern match against data structures, such as lists quite easily.  Lists are a special case as it allows you to match against the head and the tail of the given list.  By using the head::tail notation allows us to specify that we will receive the head and tail values should they be present.  Such an example might be to get the evens from a given list.

    #light

    let rec even_list = function
      | [] -> []
      | h::t when h % 2 = 0 -> h::even_list t
      | h::t -> even_list t

    let evens = [1..20] |> even_list
     

    Active Patterns

    Pattern matching in F# is extremely flexible, as you can extend what you can pattern match.  Through a mechanism called "Active Patterns", you can extend the syntax quite easily.  Let's say for instance that we want to create a pattern to determine whether a given number is either a composite number, prime number or neither.  We can define a pattern over that such as the following code:

    #light

    let is_prime x =
      let lim = int(sqrt(float(x)))
      let rec check y =
        y > lim or (x % y <> 0 && check(y + 1))
      check 2
      
    let (|Prime|Composite|Neither|) x = 
      if x < 2 then Neither
      elif is_prime x then Prime 
      else Composite

    let prime_or_composite x = 
      match x with
      | Prime -> "prime"
      | Composite -> "composite"
      | Neither -> "neither composite nor prime"

    printfn "%s" (prime_or_composite 3)

    As you can see from above, we can define the pattern using the (|pattern name|) syntax and then define the behavior from this.  Then I can use them in the pattern matching exercise below to print out whether my given number fit any of the patterns.  That's how powerful pattern matching can be.  But, can we have some of these features in C#?


    Implementing in C# 3.0

    I've had the idea to express some basic pattern matching in C# instead of having to decide whether things are a switch statement, if, else, etc.  Instead, I'd rather have the ability to specify these matches through the use of predicates for determining success and then a given action should that one be selected.  Unfortunately, that's a very limited subset of what pattern matching can achieve, but it's actually quite simple to implement in C# 3.0 through the use of extension methods and fluent interfaces.

    Let's set up a simple scenario which takes in a nullable number and matches against whether it is even, odd or null.  Below is a simple example of how that might look through the use of our extension methods and fluent interface.

    public static bool IsEven(int? n)
    {
        return n != null ? n % 2 == 0 : false;
    }

    public static bool IsOdd(int? n)
    {
        return n != null ? !IsEven(n) : true;
    }

    int? n = 3;
    var evenOdd = n.Match()
        .With(IsEven, x => "Even number")
        .With(IsOdd, x => "Odd number")
        .Else(x => "Null")
        .Do();
    Console.WriteLine(evenOdd);
     

    What this gives me is the ability to match against my current piece of data and determine the actions through my With methods and my default case with the Else method.  Each takes a lambda function which passes in the value we're matching against, and then returns a string.  The problem arises with C# though if we want our lambda to do nothing (aka void), as C# doesn't treat this as a proper return type, so you would have to switch between Func<T, TResult> and Func<T> which isn't really realistic.  So, already our design is hobbled.

    But, let's move on to what the implementation might look like.  We need a way to capture all the cases and execute them in order to find the match, else throw a MatchNotFoundException should there be no match.  Let's define that class below.

    public class MatchNotFoundException : Exception
    {
        public MatchNotFoundException(string message) : base(message) { }
    }

    public class PatternMatch<T, TResult>
    {
        private readonly T value;
        private readonly List<Tuple<Predicate<T>, Func<T, TResult>>> cases 
            = new List<Tuple<Predicate<T>, Func<T, TResult>>>();
        private Func<T, TResult> elseFunc;

        internal PatternMatch(T value)
        {
            this.value = value;
        }

        public PatternMatch<T, TResult> With(Predicate<T> condition, Func<T, TResult> result)
        {
            cases.Add(Tuple.New(condition, result));
            return this;
        }

        public PatternMatch<T, TResult> Else(Func<T, TResult> result)
        {
            if (elseFunc != null)
                throw new InvalidOperationException("Cannot have multiple else cases");

            elseFunc = result;
            return this;
        }

        public TResult Do()
        {
            if (elseFunc != null)
                cases.Add(
                    Tuple.New<Predicate<T>, Func<T, TResult>>(x => true, elseFunc));
            foreach (var item in cases)
                if (item.Item1(value))
                    return item.Item2(value);

            throw new MatchNotFoundException("Incomplete pattern match");
        }
    }
     

    What we have defined is a holder for our cases.  I'm using a Tuple<TArg1, TArg2> to hold my pairs of predicates and expressions to execute.  I've defined that as part of my Functional C# library available on CodeGallery, which should be up to date with example of functional programming using C# 3.0.  When you define an else function (or default function), we want to be able to add that to our collection as the last one to be fired, if ever, so we will define that in the Do method.

    In order to stay away from the angle bracket tax, I've created a context class which will allow me to set up my first With statement and then include the PatternMatch<T, TResult>.  This code takes in the value and then will have a With method which will return us a new instance of the PatternMatch<T, TResult>.

    public class PatternMatchContext<T>
    {
        private readonly T value;

        internal PatternMatchContext(T value)
        {
            this.value = value;
        }

        public PatternMatch<T, TResult> With<TResult>(
            Predicate<T> condition, 
            Func<T, TResult> result)
        {
            var match = new PatternMatch<T, TResult>(value);
            return match.With(condition, result);
        }
    }
     

    Lastly, I'll define a simple extension method which will allow me to pattern match against any given data type.  This will simply create a new instance of the PatternMatchContext<T> class and return it.

    public static class PatternMatchExtensions
    {
        public static PatternMatchContext<T> Match<T>(this T value)
        {
            return new PatternMatchContext<T>(value);
        }
    }
     

    Wrapping it Up

    As you can see, it's clumsy and not the most ideal as it would be in an F# solution or any other more functional programming language.  We quickly run into the limitations with the language such as dealing with Func<T, TResult> and Action<T> because C# does not treat System.Void as a type.  Wes Dyer and the Microsoft Volta team have been working on some of those issues with library approaches as well.  But, it's still interesting to try to extend C# into brave new territory. 

    I would like to see C# 4.0 and beyond continue to make inroads towards a more functional style, although I will caution that C# should stay with the object and class first approach with functional aspects, whereas leaving F# to be the functional programming first mentality.  In order to do that, there are a few big hurdles to overcome...

    As always, the sample code is available on CodeGallery at the Functional C# project.

  • Object Oriented F# - More Extension Everything

    In a previous post, I covered a few ways we can do extensions methods, properties, events and so on with F#.  After a few chats, I realized I may have missed a couple of cases that I wanted to cover today.  These two cases are extension operators and extension properties with indexers.

    With these examples, I'll try best to show you my development style, using my FsTest library from CodePlex to set up my expectations of the extensions using F# syntax.  If you're not familiar with FsTest, I recently updated it to support the F# September 2008 CTP.


    Extension Properties with Indexers

    One of the common things we like to have with some of our collections is the ability to retrieve the item by index, using the Item or this property.  With such classes as IEnumerable<'a> among others don't support such a construct, but through the use of extension properties with indexers, they can.  Let's set up how our test should be.

    #light
    open Xunit
    open FsxUnit.Syntax
    open ExtensionFSharp.CollectionExtensions

    [<Fact>]
    let items_with_correct_index_should_be_equal() =
      let items = {0 .. 2 .. 100}
      
      let actual = items.[3]
      let expected = 6
      expected |> should equal actual
     

    What I'm going to do is create a collection of 0 to 100 skipping every two numbers.  I will set my expectation that the third item should be six, which should be easy enough to test.  Running this test of course will not work as the extension property isn't defined yet.  Now, let's go ahead and define what that might look like.

    #light

    namespace ExtensionFSharp

    module CollectionExtensions =
      type System.Collections.Generic.IEnumerable with
        
        member this.Item
          with get(index) =
            Seq.nth index this
     

    What I was able to do is open the type definition of IEnumerable<'a> and add the Item property, also called the this property in C#, with a get accessor with an index.  This calls the Seq.nth which is a static function on the Seq module to return the item that I want by index.  Now, I can run my test again and check the result.

    fstest_extension_property

    Just the result we were looking for.  We could go ahead and add additional tests for out of range and inequality, but in the mean time, let's move onto another way of extending F# and the language through operators.


    Extension Operators

    One of the more interesting ideas is around extension operators.  This would give us the ability to add additional operators to our classes should we feel that they should support add, subtract and so on.  To me, it's a pretty powerful concept to be able to add such things.  Let's set up our test to see how we think it should look.

    #light

    open ExtensionFSharp.DrawingExtensions
    open Xunit
    open FsxUnit.Syntax
    open System.Drawing

    [<Fact>]
    let red_and_blue_should_equal_magenta() =
      let red = Color.Red
      let blue = Color.Blue
      let expected = red + blue
      
      actual.R |> should equal expected.R
      actual.G |> should equal expected.G
      actual.B |> should equal expected.B
     

    Our simple test is to determine if the RGB from adding red and blue should equal to magenta.  Once we try to compile, of course it doesn't work yet because we haven't defined the operator extension yet.  Now, let's implement the operator extension and see if that works.

    #light

    namespace ExtensionFSharp

    open System
    open System.Drawing

    module DrawingExtensions = 
      
      type System.Drawing.Color with
        static member (+) (c1:Color, c2:Color) =
          let r = Convert.ToInt32(c1.R + c2.R)
          let g = Convert.ToInt32(c1.G + c2.G)
          let b = Convert.ToInt32(c1.B + c2.B)
          Color.FromArgb(r, g, b)

    What we're going to do is define the operator two take two colors and then add the red, green and blue, and then create a new one from this.  We have the extension operator now defined, but going to compile it, it still won't work.  It turns out that operator extensions are not supported.  Now is the perfect time to let Don Syme know if you want them in there. 

    What options do we have then for operators?  The easiest answer is to define a custom global operator should you want that capability.  Let's define a customer operator, +$ to be the operator to handle adding of two colors together.  The first thing we need to do is change our test.

    #light

    open ExtensionFSharp.DrawingExtensions

    open Xunit
    open FsxUnit.Syntax
    open System.Drawing

    [<Fact>]
    let red_and_blue_should_equal_magenta() =
      let red = Color.Red
      let blue = Color.Blue
      let actual = red +$ blue
      let expected = Color.Magenta

      actual.R |> should equal expected.R
      actual.G |> should equal expected.G
      actual.B |> should equal expected.B
     

    The test is now changed, so let's reflect that in our new custom operator.  Once again, we'll define it inside our DrawingExtensions module in order to keep it scoped to our drawing area.

    #light

    namespace ExtensionFSharp

    open System
    open System.Drawing

    module DrawingExtensions = 
      let (+$) (c1:Color) (c2:Color) =
        let r = Convert.ToInt32(c1.R + c2.R)
        let g = Convert.ToInt32(c1.G + c2.G)
        let b = Convert.ToInt32(c1.B + c2.B)
        Color.FromArgb(r, g, b)

    Once we are able to compile and run our test, it should give us the green light like this.

    fstest_extension_operator

    Once again, just the result we've been looking for.  Not the ideal situation when I'd rather extend the type to include another operator instead of more of a global operator.  Other options could just be extending the Color class to include either a static Color.Add method or an instance Add method.  Either would work, but I would prefer the operator extension.


    Wrapping It Up

    Extension everything in F# is pretty powerful to allow us to not only create extension methods like C#, but properties, static methods, events, and indexed properties.  I would prefer to see extension operators supported as well in an upcoming CTP release as well.  I'd suggest that you let Don know if you feel the same way.  In the upcoming series, I intend to cover more object oriented principles as explained in F#, such as interfaces, classes, structs, but also the principles we hold dear such the Open/Closed Principle and so on.

  • Side Effects and Functional Programming

    One of my first posts at CodeBetter was in regards to side effects and how, when unmanaged, can be truly evil.  Today, I want to revisit that topic briefly in regards to functional programming and managing side effects.  When I was out in Redmond a couple of months ago, I had the opportunity to sit down with Erik Meijer to discuss functional programming among other topics.  In there, we discussed a number of issues around managing side effects and state in your code, and how both C# and F# don't intrinsically support such a concept.  Languages like Haskell, of course do with IO monads and other such monadic structures.  Whether languages such as F# and Erlang are not pure functional programming languages is another matter, due to the fact that you don't have to declare when you are side effecting (reading a database, writing to console, spawning a process, etc). 

    Erik will be giving a talk at JAOO about why functional programming still matters.  I think in the day and age of where Moore's law is changing, we need to recognize that functional programming has a unique place in this due to the way that it handles both purity and immutability.  Today, let's cover some of those issues when dealing with functional constructs and side effects to see what kind of an impact they can have on us.


    The Problem of Purity

    In some previous posts, I talked about function purity in regards to things you should keep in mind with a functional mindset.  In order to qualify as such, you need to meet the following criteria:

    • Evaluate with the same result given the same input, and perform no state change.
    • Evaluation of the given function does not cause observable side effects (write to console, write to database, etc)

    Things get even more clouded as we bring lazy evaluation to the table.  One of the great things that came to C# in 2.0 and especially in 3.0 with LINQ was the idea of lazy evaluation through the yield keyword.  This gave us the ability to defer work until it was absolutely needed.  That's one of the hallmarks of functional programming, especially a lazy language such as Haskell.

    Let's look at a code snippet both written in F# and the equivalent in C# and let's determine the order of side effects.  Can they be predicted here?  When do the side effects happen?  Do I just get a nice list of my integers at the end?

    F#
    #light

    let divisible_by_two n = 
      printf "%i divisible by two?" n
      n % 2 = 0

    let divisible_by_three n =
      printf "%i divisible by three?" n
      n % 3 = 0
      
    let c1 = {1 .. 100} |> Seq.filter divisible_by_two
    let c2 = c1 |> Seq.filter divisible_by_three

    c2 |> Seq.iter(fun c -> printfn "%i" c)

    C#
    static bool DivisibleByTwo(int n)
    {
        Console.Write("{0} divisible by 2?", n);
        return n % 2 == 0;
    }

    static bool DivisibleByThree(int n)
    {
        Console.Write("{0} divisible by 3?", n);
        return n % 3 == 0;
    }

    var c1 = from n in Enumerable.Range(1, 100)
             where DivisibleByTwo(n)
             select n;

    var c2 = from n in c1
             where DivisibleByThree(n)
             select n;

    foreach (var c in c2) Console.WriteLine("{0}", c);
     

    Well, what do you think?  If you said that the list will print out nicely at the end, you'd be very wrong.  In fact, our output might look something like this:

    console_impure_divisible

    Why is that?  Well, because in LINQ, the return type is always IEnumerable<T>, and in the case of F#, I was using sequences, which unlike the List<'a>, is lazily evaluated.  What can we do about it?  That's another matter altogether.  Unfortunately, the language constructs in .NET don't forbid such things, so there's no way of really preventing it, instead, you must be vigilant on your own to make sure this doesn't happen.  Spec# can help in just a little way as it can ensure state change will not occur during a given operation, but does not prevent you, nor warn you if you do such things as write to the console, logs, databases, etc.  Let's move onto another example and let's see what happens.


    Exception Management and Lazy Evaluation

    Exception management in terms of lazy evaluation is another interesting topic.  When it comes to lazily evaluated functions and structures, how do we handle exceptions that may occur is a very good question.  Let's look at an example of trying to catch an exception that may happen in our code due to a DivideByZeroException.  What do you think will happen here?  Will it be caught and just return us an empty collection?  Let's find out:

    F#
    #light

    let numbers = seq[1 ; 5; 2; 3; 7; 9; 0]

    let one_over n =
      try
        n |> Seq.map(fun i -> 1 / i)
      with
        | err -> seq[]
        
    numbers |> one_over |> Seq.iter(fun x -> printfn "%i" x)
    C#
    static IEnumerable<int> OneOver(IEnumerable<int> items)
    {
        try
        {
            return from i in items select 1/i;
        }
        catch
        {
            return Enumerable.Empty<int>();
        }
    }

    var numbers = new[] {1, 5, 2, 3, 7, 9, 0};
    foreach (var number in OneOver(numbers)) 
        Console.WriteLine("{0}", number);
     

    What did you expect?  Did we in fact catch the exception?  The answer is no, because the returned structure isn't evaluated until later, there isn't any way for this try/catch block around our code to possibly work.  The question is to you, how might you fix this?

    The logic here is fundamentally flawed.  Let's move onto another scenario, this time dealing with resource management.


    Resource Management and Lazy Evaluation

    Another area of exploration is around resource management and lazy evaluation.  How do you ensure that your resources will be cleaned up once your evaluation is complete?  It's relatively easy to make minor mistakes that may come back and haunt us.  Let's look at a quick sample of using lazy evaluation and reading a file to the completion.  What happens in the following code?

    F#
    #light

    open System.IO

    let readLines = 
      use reader = File.OpenText(@"D:\Foo.txt")
      let lines() = reader.ReadToEnd()
      lines

    printfn "%s" (readLines())
    C#
    Func<string> readLines = null;

    using(var stream = File.OpenText(@"D:\foo.txt"))
        readLines = stream.ReadToEnd;

    Console.WriteLine(readLines());
     

    The answer of course is that we get an ObjectDisposedException thrown due to the fact that the stream is long gone by the time we want to invoke our function of readLines.  Our reader has long fallen out of scope, and therefore we get that exception.  So, how do we fix it?


    Closures and Lazy Evaluation

    One last topic for this post revolves around variable instantiation around closures and what it means to you in regards to lazy evaluation.  Let's look at a quick example of some of the issues you might face. 

    C#
    var contents = new List<Func<int>>();
    var s = new StringBuilder();

    for (var i = 4; i < 7; i++)
        contents.Add(() => i);

    for (var k = 0; k < contents.Count; k++)
        s.Append(contents[k]());

    Console.WriteLine(s);
     

    What we might expect the results to be in this case would be 456.  But that's not the case at all here.  In fact, the answer you will get is 777.  Why is that?  Well, it has to do with the way that the C# compiler creates a helper class to enable this closure.  If you're like me and have Resharper, you'll notice that it gives a warning about this with "Access to modified closure".  If we change this to give ourselves a local variable inside the loop closure construct to initialize the value properly.  If we do that and change our code, it will now look like this:

    C#
    var contents = new List<Func<int>>();
    var s = new StringBuilder();

    for (var i = 4; i < 7; i++)
    {
        var j = i;
        contents.Add(() => j);
    }

    for (var k = 0; k < contents.Count; k++)
        s.Append(contents[k]());

    Console.WriteLine(s);
     

    Jason Olson has a pretty good explanation in his post "Lambdas - Know Your Closures".  But where does F# fall into this picture?  Well, let's try the first code sample written in F# to see what kind of results that we get.

    F#
    #light

    open System.Text

    let contents = new ResizeArray<(unit -> int)>()
    for i = 4 to 6 do
      contents.Add((fun () -> i))
     
    let s = new StringBuilder()
    for k = 0 to (contents.Count - 1) do
      s.Append(contents.[k]()) |> ignore
     
    printfn "%s" (s.ToString())

    When we run this code, we get what we were expecting all along, "456".  Why is that?  The F# team handles the code just a little bit differently than the C# compiler does.  This to me seems a lot less error-prone.


    Wrapping It Up

    I'd like to see how you might fix some of these issues?  What would you do differently in each example to ensure the correct result with lazy evaluation?

    Functional programming and side effects are important topics.  I hope this post shed some light on how with lazy evaluation, side effects, when not managed properly, can be quite evil.  The ideas in functional programming is to strive towards a side effect free style.  When we start introducing lazy evaluation, concurrency and other issues, we need to be mindful of side effects and how we manage them. 

    I highly encourage you to see Erik's presentation that I linked above as it contains ideas that may help make you a better programmer.  And while you're at it, watch the video of Simon Peyton Jones and Erik Meijer on Channel 9 called "Towards a Programming Nirvana".  It's definitely an eye opener!

  • Object Oriented F# - Extension Everything

    A post by Jeremy Miller caught my eye this morning in regards to extension methods in Javascript.  While I think that's pretty interesting, I don't think it's a real fair comparison.  Instead, I want to revisit C# and even F# with regards to extension methods, because there are a few things I wanted to point out.  This is the start of a series covering object oriented programming techniques and how they are used in F#.  Note that F# is not only a functional language, but it is a general purpose programming language that supports functional, imperative and object oriented techniques.  I hope this series is useful for pointing out that F# fits the need very nicely for object oriented constructs, which is seldom covered.


    Extension Methods in C# 3.0

    With C# 3.0 came the introduction of extension methods which were introduced as part of certain technologies that were LINQ-enabling.  Using these, we could add methods, and only public methods, to any given class we choose.  So, this gave us the ability to do add methods such as ForIndex to an IEnumerable<T> class such as this:

    static class Extensions 

        public static void ForIndex<T>(
          this IEnumerable<T> items, 
          Action<int, T> action) 
        { 
            var index = 0
            foreach(var item in items) 
            { 
                action(index, item); 
                index++; 
            } 
        } 


    var range = Enumerable.Range(1, 10); 
    range.ForIndex((i, item) => Console.WriteLine("{0} - {1}", i, item));
     

    But overall, I thought this was nice, but didn't go quite far enough.  Why not extension static methods, properties, events, etc?  I'm sure at one point those were considered but somehow dropped along the way, and I think it's a shame quite frankly.    

    Where should it be?  If this functionality were to exist in C#, how might it look?  Unfortunately, the way it was designed in C# 3.0, it makes it a tad hard to extend for static methods and properties.  For example, how might you declare a get or set if what you're declaring is a method such as this?

    public static bool IsEven(this int value)
    {
        get { return value % 2 == 0; }
    }
     

    Or if I were to use the property declaration style instead, it seems just as confusing as the above try at this:

    public static bool this int IsEven
    {
        get { return this % 2 == 0; }
    }
     

    Note of course none of the above code samples actually work or compile.  Unfortunately, it would seem adding static extension methods would be just as clumsy as using this technique.  So, where does this leave C# for the future?  I certainly hope that they tackle this issue and I know they will at some point.  For now, it seems through Charlie Calvert's blog, the focus for C# 4.0 seems to be around dynamic lookup and covariance/contravariance as described by Eric Lippert.  So, where extension everything falls onto the radar has yet to be determined.  That's why it's always important to let the C# team know what you want and don't want as part of the releases when they solicit feedback.

    Now that we covered that, let's look at F#, which has extension everything, and see how it works. 


    Extension Everything in F#

    As I noted above, F# is a great general purpose programming language, rooted in functional programming, but supporting object oriented programming as well.  Extension everything is a good part of the story to state that F# is a more flexible language than C#.  The way that extensions are handled are rather elegant, but also such things as creating and publishing events are much more interesting in F#.  The latter part on events will be covered in a later post.


    Extension Methods

    As with C#, F# supports standard extension methods.  There are no requirements for them to be inside a static class, instead, it has a bit of a different syntax, which looks more like we're extending a given type.  It reads much more clear as to what I'm doing than the C# solution.  To package up our extension methods, it's best to package them inside a module, which is a way of gathering values, global state, type definitions and so on.  Then to reference these groups of functions and such, you simply use the open statement to reference the module.  Let's look at a simple example of creating a ForEach method on the System.Collections.Generic.IEnumerable<'a> class.

    #light

    namespace ExtensionFSharp

    module CollectionExtensions =
      
      type System.Collections.Generic.IEnumerable with
        member this.ForEach(f:'a -> unit) =
          for item in this do
            f item
     

    Now with this, I'm able to create the ForEach method by just act like I'm creating the type.  Then I can specify the members I want to add to the given class.  Notice that I packaged this inside a namespace as well as a module, so I can reference it later.  In order to call this, I simply need to do the following:

    #light

    open System.Linq
    open ExtensionFSharp.CollectionExtensions

    let range = {1 .. 10} 
    range.ForEach(fun i -> printfn "%i" i)

    As you will notice from your Intellisense, the ForEach will show up just as all other extension methods that are declared for the IEnumerable<'a> class.  But, what if we want to work with properties as well?  Well, that option is available to us as well.


    Extension Properties

    Declaring and using extension properties in F# is just as easy as it is to create an extension method as we did above.  Let's take a simple example of creating a count property on IEnumerable<'a>.  Yes, I realize that there is a method with that same name, but I want to approach it from a functional programming perspective while using tail recursion.  I covered recursion quite a bit in my series on getting back to basics on recursion.  Recursion is a very powerful construct in functional programming in order to avoid mutable state.  F# is optimized for the tail call, so that any tail recursive call should get optimized and therefore not run into any stack overflow issues.

    #light 

    namespace ExtensionFSharp 

    module CollectionExtensions = 
       
      type System.Collections.Generic.IEnumerable with 
        member this.CountItems
          with get()
            let rec count_acc 
              (e:System.Collections.Generic.IEnumerator<'a>)
              acc =
              if e.MoveNext() = false then
                acc
              else
                count_acc e (acc + 1)
            count_acc (this.GetEnumerator()) 0

    What I was able to do is extend the IEnumerable<'a> class with a property called CountItems with a get accessor.  From there, I create an inner accumulator function which takes the accumulator and the IEnumerator<'a> used to iterate.  I have my break condition if there are no more, else I recursively tail call while incrementing the accumulator.  Simple and efficient to avoid mutable state.  In order to call this, is very simple much as above:

    #light

    open System.Linq
    open ExtensionFSharp.CollectionExtensions

    let range = {1 .. 100}
    printfn