Bloomington .NET Society – June 27

I know I’ve been quiet for a few months but don’t worry, I haven’t disappeared. Instead I’ve been hard at work on an upcoming F# book! The book has consumed most of my time but not being one to pass up a chance to talk about my obsession I’m making the trip down to Bloomington, IN at the end of the month to talk to the Bloomington .NET Society.

If you’re in the Bloomington area on June 27th and interested in learning about F#, please join us. You can find the full meeting details on the group’s site:
http://dotnet.indiana.edu/news/jun-2013-meeting
.

I hope to see you there!

Replicating F#’s using Function in C#

It didn’t take long for me to really appreciate the power offered by F#’s using function. Properly managing IDisposable instances in C# isn’t particularly problematic but the using statement really doesn’t offer a whole lot in the way of flexibility.  Sure, the block lets you create and dispose some IDisposable instance and put some arbitrary code within it but even before I entered the world of functional programming I found the syntax clunky, particularly when I only want the instance around long enough to get some value from it so I can do something with that value later. The obvious solution to the problem is to just use F# instead but unfortunately that’s not always a viable option in this C# dominated market.

Assuming that I have to work in C# I could address the situation by just putting all the code in the using block.

// C#
using(var img = Image.FromFile(@"C:\Windows\Web\Screen\img100.png"))
{
  Console.WriteLine("Dimensions: {0} x {1}", img.Width, img.Height);
}

Granted, in this contrived example I’m only writing the dimensions to the console so the image would be disposed quickly but what if I needed those dimensions somewhere else? There are a few approaches to take and honestly, I don’t like any of them all that much.

The first way would be to forego using altogether.

// C#
var img = Image.FromFile(@"C:\Windows\Web\Screen\img100.png");
var dims = Tuple.Create(img.Width, img.Height);
img.Dispose();

// Do something with dims elsewhere

This approach is probably the cleanest and is very similar to a use binding in F# but it requires discipline to remember to manually dispose of the object. In C# I’m so conditioned to define IDisposables within using blocks though that I seldom take this approach. In order to do this same task with a using statement there are basically two options, define a variable outside of the block and assign it inside the block or define a method to wrap the using statement. I generally prefer the later because it facilitates reuse and eliminates a state change.

Variable approach

// C#
Tuple<int, int> dims;
using(var img = Image.FromFile(@"C:\Windows\Web\Screen\img100.png"))
{
  dims = Tuple.Create(img.Width, img.Height);
}

// Do something with dims elsewhere

Method approach

// C#
private Tuple<int, int> GetDimensions()
{
  using(var img = Image.FromFile(@"C:\Windows\Web\Screen\img100.png"))
  {
    return Tuple.Create(img.Width, img.Height);
  }
}

// Do something with dims elsewhere

Now let’s see how this same example would look in F# with the using function.

// F#
let dims = using (Image.FromFile(@"C:\Windows\Web\Screen\img100.png"))
                 (fun img -> (img.Width, img.Height))

Look how clean that is! Wouldn’t it be nice to have something like that in C#? You’ve probably guessed if from nothing else than the title of this article that it’s entirely possible. Right now you might be thinking that you could just reference FSharp.Core and call the function from the Operators module but you’ll quickly find that more trouble than it’s worth. The using function’s signature is:

// F#
val using : resource:'T -> action:('T -> 'U) (requires 'T :> System.IDisposable)

The function accepts two arguments: resource, a generic argument constrained to IDisposable, and action, a function that accepts 'T and returns another (unconstrained) generic type, 'U. That second argument is what would prove problematic if you tried to call the function from C# since it compiles to FSharpFunc<T, TResult> instead of Func<T, TResult>. Fortunately though it’s really easy to replicate the functionality natively in C#.

Due to differences between C# and F# the C# version of the Using function needs to be overloaded to accept either a Func or an Action depending on whether you’re returning a value. You’ll see though that in either case the function is just wrapping up the provided IDisposable instance inside a using statement and invoking the delegate, passing the IDisposable as an argument. To make the code accessible you’ll want to put the IDisposableHelper class in one of your common assemblies.

// C#
public static class IDisposableHelper
{
  public static TResult Using<TResource, TResult> (TResource resource, Func<TResource, TResult> action)
    where TResource : IDisposable
  {
    using (resource) return action(resource);
  }

  public static void Using<TResource> (TResource resource, Action<TResource> action)
    where TResource : IDisposable
  {
    using (resource) action(resource);
  }  
}

Using the functions isn’t quite as elegant as in F# but it definitely gets the job done in a much more functional manner.

Not returning a value

// C#
IDisposableHelper.Using(
  Image.FromFile(@"C:\Windows\Web\Screen\img100.png"),
  img => Console.WriteLine("Dimensions: {0} x {1}", img.Width, img.Height)
);

Returning a value

// C#
var dims =
  IDisposableHelper.Using(
    Image.FromFile(@"C:\Windows\Web\Screen\img100.png"),
    img => Tuple.Create(img.Width, img.Height)
  );

Console.WriteLine("Dimensions: {0} x {1}", dims.Item1, dims.Item2);

I’d still prefer to use F# but when I can’t at least I can turn to this to make C# feel a little more like home.

IndySA – March 21, 2013

The March IndySA meeting is this Thursday.  I’m excited for the opportunity to spread around a bit more F# love as this month’s speaker.  If you’re looking for a fun way to fill the evening please join us at the SEP office in Carmel at 5:30 PM.  All of the logistics details are available on the meetup site.

I hope to see you there!

About the Talk

F# Needs Love Too

Originally developed by Microsoft Research, Cambridge, F# is an open-source, functional-first language in the ML family. Despite its lofty position as a first-class Visual Studio language for the past two releases and its cross-platform availability it hasn’t seen widespread adoption in the business world. In this talk we’ll take an introductory look at F#, exploring how its constructs and terse syntax can allow you to write more stable, maintainable code while keeping you focused on the problem rather than the plumbing.

 

GR DevDay

GR DevDay Speaker Badge

GR DevDay Speaker Badge

Last weekend I made the trek up to Grand Rapids, Michigan for the GR DevDay conference.  This was the second time I’d attended this conference but this time was special – it was my first time speaking at a conference!  I was honored to have my talk “F# Needs Love Too” selected and to have been included in line-up of speakers that included some familiar names like Eric Boyd, Jay Harris, Michael Eaton, David Giard, and Jennifer Marsman.

My talk was in the first time slot immediately following the keynote.  Considering I was up against some HTML5 and mobile development talks I was happy to see such interest in F#.  I thought the talk went well and spurred some good conversation.  Thanks to everyone that attended.  Hopefully you were inspired to take a closer look at the language and see how it can change the way you think about writing software.

Having the first time slot gave me the rest of the day to attend other sessions.  The sessions I selected were:

  1. Collaborate: Windows Phone and Windows 8 – Michael Perry
  2. Make Node.js Package. Become Famous. – Jay Harris
  3. Hot Data and Cool Cash – Joe Kunk
  4. Creating apps with high code reuse between Windows 8 and Windows Phone 8 – Jennifer Marsman

All of the talks were interesting in their own right.  Naturally I was most interested in the two Windows Phone 8/Windows 8 talks and they didn’t disappoint.  The other two sessions weren’t as immediately relevant to me but gave me some stuff to think about.

I’d like to thank the organizers for putting on yet another great conference.  I thought the event was every bit as good as the last one and was happy to be a part of it.

Custom Dark Colors for F# Depth Colorizer for VS2012

Custom F# Depth ColoringA few days ago I installed the F# Depth Colorizer extension for Visual Studio 2012. I really liked the idea but didn’t care much for the default colors used with the dark theme. Rather than alternating light and dark colors I thought it would look better with the background getting progressively lighter giving the illusion of each block being stacked on its container.

After a little tweaking I created the necessary registry entry and was pretty pleased with the result.  The image to the right shows the colors against the same code snippet used in the extension’s description.  If you’d like to use these colors just copy the registry information below into a .reg file and apply it. You’ll need to restart Visual Studio for the changes to take effect.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\Text Editor\FSharpDepthColorizer\Dark]
"Depth0"="0,0,0,0,0,0"
"Depth1"="15,15,15,15,15,15"
"Depth2"="30,30,30,30,30,30"
"Depth3"="45,45,45,45,45,45"
"Depth4"="55,55,55,55,55,55"
"Depth5"="65,65,65,65,65,65"
"Depth6"="75,75,75,75,75,75"
"Depth7"="80,80,80,80,80,80"
"Depth8"="85,85,85,85,85,85"
"Depth9"="90,90,90,90,90,90"

More information about the extension including how to customize the colors is available on Brian McNamara’s blog.

The Hacker News Effect

It has been known by many different names: the Reddit effect, the Slashdot effect, the Digg effect; but whatever the source the result is the same – a huge spike in traffic due to a popular site linking to a lesser known one. Didactic Code experienced this first hand for the first time when Why F#? gained some traction on Hacker News.

My blog traffic is predictable to the point that I occasionally joke about how I can tell what time it is by looking at the stats. Lately my quiet little node on the Web had been seeing around 200 views on weekdays and generally about 1/4 of that on weekends. Sunday evening though I noticed something unusual – my view count had climbed to over 1000. The blog stats showed the traffic was coming from Hacker News so naturally I started watching to see how high the numbers would climb. Sunday ended with 1,575 views and the momentum carried on well into Monday until after the article peaked at #13.

Hourly Traffic

Hourly Traffic

The hourly traffic graph from the WordPress banner shows traffic for the past 48 hours.  It maxed out at 705 views.

Daily Traffic

Daily Traffic

The daily traffic graph shows all traffic for the past 30 days. You can imagine my surprise when the traffic shot up on Sunday.

Weekly Traffic

Weekly Traffic

The weekly traffic graph shows 31 weeks of history. You can clearly see the annual dip around the holidays followed by this week’s spike.

Monthly Traffic

Monthly Traffic

The monthly graph is the most interesting to me because it shows how steadily my traffic has increased over the years and what an anomaly like this looks like in the life of a small blog.

For as much excitement as I got out of this I was really happy about the discussion the post generated here, on HN, and on Twitter.  I didn’t jump into the HN conversation but I really enjoyed reading the comments, particularly those comparing languages that I haven’t even thought about looking at.  So, to everyone that took the time to read my post and those that joined in on the conversation – thank you!

GR DevDay – March 2, 2013

If you’re looking for a great developer conference in the Grand Rapids, MI area I highly recommend checking out GR DevDay. This year the conference is being held on March 2 at Calvin College. The organizers have lined up a  great selection sessions covering a wide range of topics and technologies. Whether you’re developing for the cloud, desktop, or mobile spaces you’ll be sure to find something of interest.

I’m honored to be included among this year’s speakers. If you’re interested in an introduction to F# be sure to check out my session:

F# Needs Love Too!

Originally developed by Microsoft Research, Cambridge, F# is an open-source, functional-first language in the ML family. Despite its lofty position as a first-class Visual Studio language for the past two releases and its cross-platform availability it hasn’t seen widespread adoption in the business world. In this session we’ll take an introductory look at F#, exploring how its constructs and terse syntax can allow you to write more stable, maintainable code while keeping you focused on the problem rather than the plumbing.

I hope to see you there even if you don’t attend my session.
…but please do
…you know you want to!