Languages

Back to Basics: Streamlining the StringBuilder

To get back in the habit of blogging I thought I’d start by trying to breathe some new life into one of the oldest pieces of the .NET Framework – the StringBuilder. A few years ago I wrote about an aspect of the StringBuilder class that’s often overlooked – it’s fluent interface. Back then I speculated that one reason the fluent interface is so rarely used is that virtually every StringBuilder example, including those on MSDN, fail to highlight it by using a more imperative style. (more…)

.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.

 

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.