Try F# Sabbatical

I am extremely pleased to be able to announce that I have started a two month sabbatical from my current employer, SRT Solutions to join Microsoft Research’s Try F# team as they push towards release. Enormous thanks are due to Dianne Marsh, Bill Wagner, and the rest of the team at SRT for stepping up and allowing me to take this opportunity on very short notice. They rock. Kudos are also in order for the team at Microsoft Research for reaching out to the F# community for help with the site. I’m really excited about this opportunity, and I hope it will be a win-win-win for everyone!

One of my first tasks is to investigate possible extension points that advanced users can use to build more sophisticated tutorials/demos/presentations, so if you have any ideas, feel free to shoot them my way! Of course, if you have any other feedback on the preview version of the new Try F#, I’d love to hear it.

Thanks again to everyone who helped make this happen, and thanks to those of you who have already offered support. I’ll do my best to write some new blog posts based on my experiences, but no promises!

Posted in Uncategorized | 1 Response

C# Async Examples in F# – Part 3

This post is the third of a series where I am converting the C# 101 Async Samples into F#. See below for the other entries in the series:

C# Async Examples in F# – Part 1

C# Async Examples in F# – Part 2

The third async example deals with running operations in parallel. The C# version is structured similarly to the second example, but it starts the string downloads immediately instead of awaiting each result.

public async void AsyncIntroParallel()
    Task<string> page1 = new WebClient().DownloadStringTaskAsync(new Uri(""));
    Task<string> page2 = new WebClient().DownloadStringTaskAsync(new Uri(""));
    Task<string> page3 = new WebClient().DownloadStringTaskAsync(new Uri(""));

    WriteLinePageTitle(await page1);
    WriteLinePageTitle(await page2);
    WriteLinePageTitle(await page3);

For the F# version, I changed things a bit from the last example to use a more functional style:

member this.AsyncIntroParallel = async {
    let read url = (new WebClient()).AsyncDownloadString(Uri(url))

    let! results = [ ""; 
                     "" ]
                   |> read
                   |> Async.Parallel
    |> Seq.iter this.WriteLinePageTitle

First, I construct an async workflow for each URL that performs the download. Next, I use the Async.Parallel combinator to tell the operations to start in parallel. Finally, I print the results in order using Seq.iter.

I mentioned this in Part 1, but this example really shows the difference in the way asynchronous operations are started between C# and F#. In C#, tasks are hot, so the three page requests occur immdeidately after the tasks are created. F# requires you to start async blocks by hand, but this gives you some additional flexiblity. Since the call to Async.Parallel at the end of the function is what triggers the parallelism, you can change that call to achieve different behavior while keeping the rest of the code the same. For example, if you want to switch back to synchronous behavior (perhaps for testing), you can do that as follows:

member this.AsyncIntroParallel = async {
    let read url = (new WebClient()).AsyncDownloadString(Uri(url))

    let results = [ ""; 
                     "" ]
                  |> read
                  |> Async.RunSynchronously
    |> Seq.iter this.WriteLinePageTitle

I prefer the flexibility and composability that the F# approach emphasizes. However, I like that C#’s hot starting behavior results in slightly less verbose code for simple examples.

Posted in Async, C#, F# | 2 Responses

C’est la vie

As you may have noticed, someone decided it was a good idea to hack my blog. I’m actually flattered that someone took the time to do it, so thanks for the compliment to whoever did it! Next time I would appreciate a more direct forms of flattery (hint: money).

I’ve re-deployed to a fresh instance of WordPress, but as these things go, it’s possible that there’s still a backdoor or other exploit left over from the first attack. I’ll try to monitor things more closely over the next few days for suspicious activity.

Most site functionality should be working, but feel free to let me know via twitter or some other mechanism if you notice anything funky.

Posted in Uncategorized | 2 Responses

C# Async Examples in F# – Part 2

This post is the second of a series where I am converting the C# 101 Async Samples into F#. See below for the other entries in the series:

C# Async Examples in F# – Part 1

C# Async Examples in F# – Part 3

The second C# Async example deals with making multiple asynchronous web requests in serial. It’s pretty similar to the first example, but the nature of the example makes a few differences between the C# and F# async models more obvious.

Lets start with the C# sample:

public async void AsyncIntroSerial()
    var client = new WebClient();

    WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri("")));
    WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri("")));
    WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri("")));

I’ll first show the simplest possible approach to convert it to F#:

let AsyncIntroSerialWithCodeSmell = async {
   let client = new WebClient()
   let! result1 = client.AsyncDownloadString(Uri(""))
   this.WriteLinePageTitle result1
   let! result2 = client.AsyncDownloadString(Uri(""))
   this.WriteLinePageTitle result2
   let! result3 = client.AsyncDownloadString(Uri(""))
   this.WriteLinePageTitle result3

This approach is clearly smelly. F# evaluates async expressions using the let! syntax which also binds a name to a value. That means that you need to create a temporary variable to store the result of each async download. This was also true in the first async example, but it’s significantly more ugly here. Fortunately, you can easily rewrite this code to clean things up.

let AsyncIntroSerial = async {
    let client = new WebClient()
    let readAndWrite url = async {
        let! result = client.AsyncDownloadString(Uri(url))
    do! readAndWrite ""
    do! readAndWrite ""
    do! readAndWrite ""

You can take advantage of F#’s support for nested function definitions and closure to rewrite the code in a DRY manner. I like this refactoring, but I do wish that F#’s computation expression builder syntax allowed me to run an async operation inline like the C# await syntax.

Posted in Async, C#, F# | 1 Response

C# Async Examples in F# – Part 1

This post is the first of a series where I am converting the C# 101 Async Samples into F#. See below for the other entries in the series:

C# Async Examples in F# – Part 2

C# Async Examples in F# – Part 3

Some of you may be familiar with my boss and C# guru Bill Wagner’s series on Async Samples in C#. For those of you who aren’t familiar, he has been working through the 101 Async Samples and posting his comments for each sample. The series is well worth a look if you’re looking to learn about the upcoming async features of C#.

Starting with this post, I’ll also be working through the 101 Async Examples, but I’ll be re-writing them in F#. For each example, I’ll also briefly discuss the tradeoffs between the F# and C# async models. I think that it will be a fun way to compare the C# and F# examples, and I hope to learn a few things along the way. Maybe you will, too!

I’ll try to keep these posts on the short side (no promises), but if you want an in depth comparison of the C# and F# async models, I highly recommend this excellent series on Asynchronous C# and F# by Tomas Petricek.

With the intro out of the way, let’s take a look at the first sample which makes an asynchronous web request and outputs the result. In C# that looks like this:

public async void AsyncIntroSingle()
    WriteLinePageTitle(await new WebClient().DownloadStringTaskAsync(new Uri("")));

And now the F# version:

let AsyncIntroSingle() =
    async {
        let client = new WebClient()
        let! result = client.AsyncDownloadString(Uri(""))
        do WriteLinePageTitle(result)
    |> Async.StartImmediate

The samples look different on first glance, but the structure is actually fairly similar if you work from the inside out. Both samples start with an extension to WebClient to perform an asynchronous web request. Next, a keyword is used to yield control flow while the async operation occurs. C# uses the await keyword to do this while F# uses let! (more on this later).  Finally, the result is passed to the WriteLinePageTitle function to print the result.

The outermost layer is where things start to differ. The C# version starts the async operation immediately, but the F# requires some extra work. This is one of the major differences between the C# and F# models. C# tasks start as soon as you create them, but F# requires you to manually start the task. For simple examples, this makes the C# version cleaner. However, the F# model gives you more power to compose tasks and decide how they will run.

The last thing that I will point out is F#’s async { } block vs the async keyword on the method signature in C#. These constructs both indicate that asynchronous operations will be performed within a context. In C# this context is a method, but in F# the context is a workflow. This seems like a minor point, but it hints at the significant difference in implementation between C# and F# async. Async in C# is implemented by the compiler, but F# async is not a special language hack. F# Computation Expressions (Monads) provide the underpinnings for the F# async model. An explanation of Computation Expressions is well beyond the scope of this post, but know that the same magic that makes the let! keyword perform async operations in this sample can be extended to do other powerful things (like building sequences) in F#.

Posted in Async, C#, F# | 4 Responses

Five Reasons the MVP Summit was Awesome

At the start of March, I was fortunate enough to follow up my awesome time at the Java Posse Roundup with an equally awesome time at Microsoft’s MVP Summit. It was my first time at a Summit, so much like the Roundup, I didn’t know what to expect. In the end, it was every bit as amazing as I hoped it would be. Here are five reasons why:

1. Community

The energy of the MVP community was great. It’s hard to describe the feeling of being surround by hundreds of the most passionate thought leaders in the Microsoft world for three days, but it’s wonderfully refreshing. I really enjoyed the opportunity to pick the brains of experts in technologies that I’m not as familiar with.

While the MVP community as a whole was wonderful, being a part of the F# MVP sub-community was even more rewarding. I spent most of the week hanging out with fellow F#ers Richard Minerich, Daniel Mohl, Talbott Crowell, Aaron Erickson, Robert Pickering, and Justin Lee. While I knew many of them from twitter, it was incredibly exciting to meet and exchange ideas in person. We may have had to hand write “F# MVP” on our nametags, but that didn’t stop me from feeling more connected to the F# community than I ever have before. Being around so many passionate F#ers inspired dozens of new ideas for F# projects, and I hope to be able to transform some of those ideas into reality later this year.

2. “Open Spaces” (The hallway track)

The summit was definitely not an open spaces conference like the Java Posse Roundup, but the impromptu conversations that took place were just as great. Where else can you see Mads go head to head with Miguel De Icaza on  the future of C#? How about talking C# with Anders and asking him to give F# a little more love in his next keynote (which I may or may not have done). Not to mention all the other direct contact that you have with dozens of product team members. While the topics ranged from TDD to language design to the future of different technologies, all of the hallway discussions were filled with incredibly smart people, and the conversation was rich with great ideas.

3. NDA Access

Before I was a MVP, I was frequently annoyed by Summit attendees who tweeted things like, “[REDACTED] is going to be so cool!!!”. I made sure to keep that in the back of my head during my time at the Summit, but it’s undeniably fun to get a sneak peek of the future. Day 2 and 3 of the conference were all about showing us the future and giving product teams feedback on what to improve before things go public. Day 3 was particularly awesome since Don Syme gave the F# MVPs a first hand chance to play around with some of the new F# features. The only downside is that it’s even harder for me to wait for the next release of F#!

4. Global Reach

The MVP Community is a global community. At the Summit, I got to know a lot of people from people from places outside of the US like Canada, Singapore, and the UK. Of course, there were also MVPs from all corners of the US in attendance. This wide variety of backgrounds led to a diverse set of opinions and helped me to make a bunch of new friends from around the world. Being part of the worldwide community is a great feeling, but it also meant that I felt a stronger connection to people from the Midwest. I even got to know a few people from my local area that I never got a chance to meet at local events!

5. Great Accommodations

Simply put, Microsoft takes care of you while you’re at the Summit. The week was filled with free drinks, free food, and free caffeinated beverages to keep you energized after you were up late at fun evening events. Oh, and they also rented Safeco Field for the attendee party. If a party in a baseball stadium isn’t the perfect way to cap off two weeks of awesome conferences, I don’t know what is!

Posted in Conferences, F# | Leave a comment

Five Reasons the Java Posse Roundup was Awesome (from a “.NET guy”)

I recently had the opportunity to attend the Java Posse Roundup, a small open spaces conference put on by the Java Posse and Bruce Eckel. I have mostly focused on the .NET stack professionally, and while I work hard to avoid being a zealot, I still expected to be a .NET outcast in a world of Java developers. Beyond that, I had no idea what to expect from the conference. I had never listened to a Java Posse podcast, and I only went because conference regulars Barry Hawkins, Dianne Marsh, and Joe Nuxoll (a posse member) said that I would enjoy it.

The result? Nothing short of awesome. I had an amazing time. The conference members were very welcoming to a .NET “outsider”, inspiring ideas were exchanged, and I learned a lot about the Java world. Here are five specific reasons why it was worth the trip:

1. Open Spaces

If you’ve never experienced open spaces, you need to. In short, open spaces are an effort to facilitate the organic discussions that happen in hallways and around bar tables at normal eyes forward conferences. Attendees post ideas for discussion topics on sticky notes and place them in a time slot, and people get together and talk around that topic. Whoever shows up is the right group, whatever happens, happens, and if you aren’t interested in the topic, it is your responsibility to find (or form) a group that does interest you.

I previously experienced open spaces at CodeMash, but the Roundup takes it to another level. All of the sessions are open spaces sessions, and all of the attendees really buy into the idea of open spaces, so the conversations that happen are incredible. Another interesting twist at the Roundup is that most of the sessions are recorded which I think helps to make sure people contribute positively to the discussion.

If you still aren’t convinced that the format makes for awesome content, here’s how you know: I was out until at least 2 every night, and I still woke up at 8 every morning to make the 8:30 sessions. There’s no way that I’d make it 5 days at any other conference without skipping at least one morning session.

2. Lightning Talks

Two evenings of the conference were devoted to lightning talks, which are presentations lasting 5 minutes or less. There were no limits on topics, and variety was definitely encouraged; topics ranged from taxidermy to Continuous Integration environments and everything in between. The lightning talks educated me about a wide variety of things, but they also helped me learn the attendees interests better which led to even more interesting discussions and stronger connections later in the conference.

Don’t believe me? Check out the lightning talk recordings.

3. A Small, Welcoming Community

Unlike most conferences, there were only around 50 attendees at the Roundup, and that was a good thing. Aside from the fact that the town of Crested Butte doesn’t scale well for a much bigger conference, the number of attendees meant that I knew almost everyone there by name by the end of the week. At most larger conferences, you may meet one or two folks that you get to know well, but at the Roundup I was able to develop great connections with dozens of thought leaders in the industry. That type of exposure is invaluable and is much more difficult to encounter at larger conferences.

4. Cross Training

As a “.NET guy”, I learned a lot about the culture and thinking of folks in the Java Community. Some folks were even interested in picking my brain about F#. I spent a couple of the afternoons working with Dick Wall (another posse member) and others working to get the F# Koans running on Ubuntu. Along the way, I was able to learn a lot about Scala by asking Dick to compare the F# features we were working with to Scala. Cross training between platforms and communities like this is incredibly rewarding and educational, and it’s something that I wish we did more of as an industry.

5. Crested Butte

A picture’s worth a thousand words:


Best. Conference Destination. Ever. The one downside? Bonding over skiing, while fun, makes late nights of socializing even more tiring in the morning.

Posted in Conferences, Java | 3 Responses

F# on (Ubuntu) Linux with Mono and Monodevelop

This week, I’m attending the Java Posse Roundup to learn about the interesting things happening on the JVM, meet smart people, and hopefully write some Scala and Clojure code. One of the more surprising emails that I got after registering for the conference came from Dick Wall who asked if I could take an afternoon during the conference to hack some F# with him. Dick prefers to run Ubuntu, and I have wanted to revisit F# on Ubuntu ever since I played around with it a few months back, so I set about installing F# and getting it to run with Monodevelop in Ubuntu.

Below is the process that I used to get everything working on my machine. I don’t claim that this is the best way to do things or that it will even work for anyone else. However, I didn’t find much up to date documentation on the web about running F# on Ubuntu, so hopefully this useful to others. I’ll do my best to keep this up to date, so feel free to post comments on your experiences.


Unlike most installs on Ubuntu, mono is tricky. For various reasons, the mono packages in the Ubuntu repositories are significantly out of date, so you will have to build from source to get even semi-recent updates. I decided that I did not want to overwrite the mono installation that ships with Ubuntu, so these instructions will set you up with a parallel mono installation in /opt/mono.

Getting Started

Before you get started, you’ll need to make sure a few prerequisites are installed. You probably already have most of these if you’re a dev.

sudo apt-get install git build-essential autoconf libtool automake

Next, create (or make sure you have permission to access) /opt/src and /opt/mono since that’s where you’ll be putting all of the fresh mono bits.

cd ~
mkdir src 
sudo mv ./src /opt 
mkdir mono 
sudo mv ./mono /opt

Installing mono

It’s easy to install a parallel mono environment once you know what you’re doing. First, you’ll need a couple of dependencies.

sudo apt-get install bison gettext

Next, download the mono source. I chose to install mono 2.10 (which was just released at the time of this writing), but you can install whatever version you’d like by modifying the git commands below.

cd /opt/src 
git clone git:// mono 
cd mono 
git branch mono-2-10 remotes/origin/mono-2-10 
git checkout mono-2-10

Now build and install mono. Note: don’t forget the –prefix option since that’s how you avoid overwriting the default mono installation.

./ --prefix=/opt/mono 
make install

Setup a Parallel mono Environment

Now that your parallel instance of mono is installed in /opt/mono, you need a way to tell your bash environment to use it instead of Ubuntu’s default mono when you’re developing. You can do that with a short bash script as described on the parallel mono page.

You can create the script anywhere. I put mine in my home folder

vim ~/mono-dev-env

Add the following lines to your script to configure the parallel mono environment.

export ACLOCAL_PATH=$MONO_PREFIX/share/aclocal 
export PKG_CONFIG_PATH=$MONO_PREFIX/lib/pkgconfig:$GNOME_PREFIX/lib/pkgconfig 

Now tell bash to use your new environment.

source ~/mono-dev-env

You can test that everything is working by running mono -V. Note that if you close your terminal window at any point during the rest of the install, you will have to source the mono-dev-env script again.

$ mono -V 

Mono JIT compiler version 2.10 (mono-2-10/1630b8e Thu Feb 10 18:40:28 EST 2011) 
Copyright (C) 2002-2011 Novell, Inc and Contributors. 
    TLS:           __thread 
    SIGSEGV:       altstack 
    Notifications: epoll 
    Architecture:  x86 
    Disabled:      none 
    Misc:          softdebug 
    LLVM:          supported, not enabled. 
    GC:            Included Boehm (with typed GC and Parallel Mark)

Install F#

There are a couple of ways to get F# running under mono, but I chose to also build F# from source. A mono-friendly version of the F# source lives on github. Since you will use F# Interactive, you’ll also want to grab libgdiplus, which F# Interactive requires to run properly.

sudo apt-get install libgdiplus

With that out of the way, download, build, and install F# from github. Again, don’t forget the –prefix option. Now is a good time to grab a drink since F# can take a while to build.

cd /opt/src 
git clone git:// 
cd fsharp 
./configure --prefix=/opt/mono 
make install

When you’re done, you can run the following to make sure everything went well.

Microsoft (R) F# 2.0 Compiler build (private) 
Copyright (c) 2002-2010 Microsoft Corporation. All Rights Reserved.

error FS0207: No inputs specified

Note that you can also run F# interactive at this point, too.


Microsoft (R) F# 2.0 Interactive build (private) 
Copyright (c) 2002-2010 Microsoft Corporation. All Rights Reserved.

For help type #help;;

> exit 0;;

Right now you already have a full blown F# development environment at your fingertips, so you could stop at this point. I prefer to have monodvelop since I find that having mouse-over type information is very helpful when writing F#.

Install monodevelop’s Dependencies

Before you can install monodevelop, you’ll need to grab a few of dependencies, but those dependencies have a few dependencies of their own. Fortunately, you can get all of those from the Ubuntu repositories.

sudo apt-get install libgtk2.0-dev libgconf2-dev libglade2-dev libgnomecanvas2-dev libgnomeui-dev

Now you’re ready to install gtk-sharp, the first monodevelop dependency. Check out and build the most recent release of gtk-sharp (which at the time of this writing is 2-12).

cd /opt/src 
git clone git:// gtk-sharp 
cd gtk-sharp 
git branch gtk-sharp-2-12-branch remotes/origin/gtk-sharp-2-12-branch 
git checkout gtk-sharp-2-12-branch 
./bootstrap-2.12 --prefix=/opt/mono 
make install

Next up is mono-addins.

cd /opt/src 
git clone git:// mono-addins 
cd mono-addins 
./ --prefix=/opt/mono 
make install

Finally, you’ll also need gnome-sharp.

cd /opt/src 
git clone git://
cd gnome-sharp
./bootstrap-2.24 --prefix=/opt/mono 
make install

Install monodevelop

With the dependencies out of the way, you’re clear to install monodevelop. I  got version 2.4 of monodevelop since the F# plugin does not work with the latest builds of monodevelop at the time of writing.

cd /opt/src 
git clone git:// 
cd monodevelop 
git branch 2.4 remotes/origin/2.4 
git checkout 2.4 
./configure --prefix=/opt/mono --profile=core 
make install

Install fsharpbindings

The fsharpbindings project is a plugin that makes adds support for F# to monodevelop. I had trouble getting the latest source working with a parallel mono 2.10 environment on Ubuntu, but I was able to fix the problems with my own branch of the plugin. I’ve put in a pull request, but for the time being, pull from my fork. I’ll update this post once the main fsharpbindings project works with Ubuntu and mono 2.10.

cd /opt/src
git clone git:// 
cd fsharpbinding/ 
make install

One Last Bit of Setup

You’re almost there. One last bit of setup is required since the current version of fsharpbindings uses different names for the F# compiler and F# Interactive executables. Create symlinks to get the bindings to work.

cd /opt/mono/bin 
ln -s ./fsi ./fsharpi 
ln -s ./fsc ./fsharpc

Try it Out!

If everything went according to plan (yeah, right), you should have a full blown F# IDE. Test it out!

Note: When testing the install, I received several weird errors the first time I created a F# project in monodevelop. Monodevelop segfaulted once and also complained about not being able to find “System.Array”. I’m not sure why these errors occur, but simply restarting monodevelop fixed them for me. I’ll update if and when I figure out more.

cd ~ 

You should be able to try out F# by running code in the F# interactive window similar to the one in Visual Studio.

You can also create a console application.


I hope you found the above install process useful, but feel free to leave comments or otherwise contact me if you find problems. F# on mono has come a long way since I last played around with it, and I’m looking forward to watching (and helping) things progress more in the future.

Special thanks to Jay Wren for helping me put this together!

Posted in F#, mono | 19 Responses

C# Expressions vs. F# Quotations: A Syntax Comparison

In C# the easiest and most common way to create an expression is by implicitly converting a single line lambda into an expression:

Expression<Func<int, int>> expression = x => x * 10;

This implicit conversion is great for some APIs, like the mocking library MOQ:

public void MoqSample()
    var mock = new Mock<IList<int>>();
    mock.SetupGet(l => l.Count).Returns(15);
    Assert.AreEqual(15, mock.Object.Count);

When I use MOQ, I’m glad that the l => l.Count lambda automatically gets converted to an expression, but there are pitfalls that you need to be wary of with this conversion.

It’s often good practice to refractor complicated lambdas into helper methods for reuse and code clarity:

//Using a simple lambda predicate
var values =
    .Where(x => x > 15);
//refactoring the predicate into a helper method
//NOTE: in practice, I'd probably leave this as a lambda
//since it's neither complicated nor multi-purpose.
public bool Condition(int x)
    return x > 15;

var values =

However, you need to be careful when using this technique with some APIs. For example, the following example uses LINQ to SQL to translate a Where predicate into a SQL call:

using (var context = new SampleDataContext(""))
    context.Foos.Where(x => x.Bar == "a match");

If you refactor this predicate into a helper method, the result is not what you may expect:

public bool Condition(Foo x)
    return x.Bar == "a match";

using (var context = new SampleDataContext(""))

The helper method is not implicitly converted into a predicate like the lambda version, but the code still compiles. Instead, the Where method from LINQ to Objects is called. The method will still return the same result, so your integration tests won’t fail, but the behavior has changed. Instead of translating the Where predicate into SQL, the query will pull all of the Foo objects from the database and filter in memory using LINQ to Objects. This can have a huge impact on performance, and only load testing or QA testing this particular part of the application will catch it. Ouch.

The F# version of expressions is quotations, but F# doesn’t implicitly cast lambdas into quotations. Instead, you have to explicitly wrap code using a special notation:

let quotation = <@fun x -> x = "a match"@>

Honestly, I think that this syntax is ugly, but it means that you can’t accidently call the wrong version of an overloaded method like you can in C#. If you translate the LINQ to SQL example from above into F#, it looks like this:

//NOTE: The following won't compile since LINQ to SQL 
//      doesn't support Where with a quotation
use context = new SampleDataContext("")
let values = context.Foos.Where(<@fun x -> x.Bar = "a match"@>)

Here, the conversion of the predicate into a quotation is explicit. Unfortunately, you can’t have your cake and eat it too, so an F# version of MOQ would also require you to tag your lambdas even when there is no danger of calling the wrong overloaded function:

//NOTE: The following won't compile since MOQ doesn't
//      support SetupGet with a quotation
let MoqSample() =
    let mock = new Mock<IList<int>>()
    mock.SetupGet(<@fun l -> l.Count@>).Returns(15)
    Assert.AreEqual(15, mock.Object.Count)

Ultimately, choosing between implicit and explicit casting is a game of tradeoffs. Until I encountered the overloading problem with C#’s implicit style, I found F#’s explicit approach to be ugly and unnecessary. Now that I better understand some problems of implicit casting to expressions/quotations, I appreciate the explicit approach- even if I’m still not a big fan of the characters used to make the tags.

Posted in C#, F# | Leave a comment

Revisiting Elevate: Seq.pairwise for C#

I’ve been working on a few different projects over the last few months including some work outside of the .NET space. This has been good for my clients, but not so good for Elevate. Fortunately, I found some time the other day to add a new feature: a pairwise implementation for C#.

In F#, the Seq.pairwise function enables you to walk a sequence two elements at a time. In F# Interactive, it looks like this:

> [0..3]
  |> Seq.pairwise;;
val it : seq<int * int> = seq [(0, 1); (1, 2); (2, 3)]

It’s an especially useful function to have in your arsenal if you need to compute deltas in a sequence:

> [0;2;5;6;2;5]
  |> Seq.pairwise
  |> (fun (l, r) -> r - l)
  |> Seq.toList;;
val it : int list = [2; 3; 1; -4; 3]

I chose to implement pairwise a little differently in C#. Because C# doesn’t have language support for pattern matching against tuples, I find that they are more clumsy to use than in F#. So, instead of having pairwise return an IEnumerable of Tuples, I created two overloads of pairwise.

One overload accepts a Func to map elements from an IEnumerable:

public void PairwiseSelect()
    //given a sequence
    var values = 0.Through(5);

    //we can walk the list two elements at a time by using pairwise
    //and find the sum of the two elements
    var result = 
        .Pairwise((x, y) => x+y);

    Assert.That(result, Is.EqualTo(new[] { 1, 3, 5, 7, 9 }));

While the other accepts an action to perform while walking an IEnumerable two elements at a time:

//given a sequence
var values = 0.Through(5);

//we can also use pairwise to execute an action while
//walking a sequence two elements at a time
values.Pairwise((x, y) => Console.WriteLine(x*y));

I don’t use pairwise as frequently as some functions in Elevate/LINQ/Seq, but it’s very useful when you need it. Hopefully I’ll find more time in the upcoming weeks to contribute more regularly to Elevate!

Posted in C#, Elevate, F# | Leave a comment