Software Development

2013 in review

The WordPress.com stats helper monkeys prepared a 2013 annual report for this blog. I’m disappointed that I posted only 18 articles this year – it’s almost like I’ve been busy with another project! With The Book of F# nearly complete, I hope to get back here a bit more often in 2014.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 49,000 times in 2013. If it were a concert at Sydney Opera House, it would take about 18 sold-out performances for that many people to see it.

Click here to see the complete report.

.NET Users of Fort Wayne – March 19

To celebrate the release of my new book, The Book of F#, I’ll be back in Fort Wayne, IN to talk to NUFW on March 19. Instead of the usual technical talk, this will be an open-ended discussion of my experiences writing a technical book but I’m sure that F# will find its way into the conversation at least a few times.

If you’re in the Fort Wayne area and would like to join us, we’ll be meeting at the Cole Foundation Conference and Training Center (3213 Stellhorn Rd) at 6:00 PM. I’ll be giving out a few copies of the book as door prizes so you won’t want to miss this!

Fibonacci Sequence

As The Book of F# is nearing completion I’ve suddenly found myself with a bit of something people like to call spare time. This concept has been pretty foreign to me over the past nine months so as a way to fill that time I started looking at the Project Euler problems. I’m not far along yet (my math skills have gotten rusty over the years) but so far it has been a fun exercise.

Problem 2, involves calculating the sum of the even Fibonacci numbers less than 4,000,000. In the spirit of the project, I won’t divulge my entire solution (though it won’t be hard to fill in the gaps), but I thought the algorithm for generating Fibonacci numbers was interesting so I wanted to explore it a bit along with some interesting ways we can use it to create sequences in F#. (more…)

The Book of F#

The Book Of F#Earlier this year (late February to be exact) my life took an interesting turn: a publisher approached me about writing an F# book. Writing a book had been something that I’d thought of doing for some time but it was never something I gave any serious consideration. After some discussion with my wife, mostly about the time commitment, I decided to go ahead with the project. Since then, a mix of writing, reviewing, revising, and the variety of other activities that go along with getting a book on the shelves have consumed most of my nights and weekends.

After months of work, I’m very excited to announce that The Book of F#: Breaking Free with Managed Functional Programming will be published by No Starch Press! The book is scheduled for release on March 22, 2014 but No Starch is accepting pre-orders now! By pre-ordering from No Starch with the coupon code PREORDER, you can save 30% off the cover price of $44.95.

If you’re an experienced .NET developer that would like to break free from the chains of C# and Visual Basic or someone that’s just curious about the language, this book is for you. The Book of F# will introduce you to the basics of the language and walk you through features such as currying, partial application, pattern matching, discriminated unions, record types, units of measure, type providers, and a plethora of other concepts. Throughout the book you’ll see examples of how F#’s terse syntax and functional-first nature will help you be more productive and produce code that’s more predictable than that of many modern languages.

F# has been getting a lot of attention lately. If you’re even remotely curious as to why, I hope you’ll consider adding this book to your collection.

.NET Users of Fort Wayne – August 21

On August 21st I’ll once again venture out of my cave for a trip to Fort Wayne, Indiana where I’ll spread more F# love with my friends at NUFW.

If you’re in the Fort Wayne area and want to learn about how F# and functional programming principles can improve your software, please join us. The doors open at 6:00 for networking and the main event begins at 6:30. Be sure to check NUFW ‘s events page for the latest logistics information.

Microsoft MVP – Visual F#

If you’ve spoken with me or have been following this blog for any time you know that over the past year I’ve developed a bit of an obsession with the F# language. You’ve probably also noticed that fresh content here has been a bit, well, lacking over the past few months as I’ve focused on some speaking engagements and writing an as yet untitled F# book. I was very surprised, ok, shocked, when earlier this week I received word that I’ve been selected as a 2013 Microsoft MVP for Visual F#! I’m extremely honored to have received this recognition and will do everything I can to continue promote and advance this fantastic language.

I owe a debt of gratitude to the Indiana development community that I’ve been part of for so many years, particularly the user groups in Indianapolis, Fort Wayne, and Bloomington. Thank you for your all of your support and encouragement.

If you’re interested, you can find my MVP profile here: http://mvp.microsoft.com/en-us/mvp/David%20Fancher-5000148

On a related note, if you haven’t read about the new language features or tooling support in F# 3.1 and Visual Studio 2013, be sure to take a look at the F# Team blog.

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#

Update – 5 April 2014

I’ve reconsidered the approach discussed here. This post is still worth reading for the context and motivation behind creating a Using method in C# but the updated approach works better and passes static code analysis. You can find the updated approach at the address below:

https://davefancher.com/2014/04/05/revisiting-the-using-function/

Thanks!

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.