List Comprehensions in F#

At my current contract, we’ve started a weekly brown bag session on F# and we’ve had two sessions so far, one on “what the hell are we doing” and a second on the basic syntax of the language. I presented for the second one and hit most of the high points but something I missed is that F# has list comprehensions. Lots of times I find myself writing C# code and wishing for the list comprehensions from Python.

Pre-Linq, you might build up a list like this:

List squares = new List();
for (int i = 0; i < 11; i++) { squares.Add(i * i); }

Post-Linq, it's a little cleaner but still kinda ugly:

List squares1 = Enumerable.Range(1, 10).
.Select(number => number * number).ToList();

At least the amount of code you are writing is much less but it's still not very clean.

But in F#, with list comprehensions, you get this:

let num = [for x in 1..10 -> x * x]

Wow, how freaking cool is that! Most of the succinctness obviously comes from F#'s strong type inference but in this day and age, why don't all languages have that?

List comprehensions get even more interesting when you have multiple lists that you want to work into a single list. For example, say you have two lists, each containing vectors and you want a list of the products of the vectors in the two lists.

let vec1 = [1;2;3]
let vec2 = [4;5;6]
let products = [for x in vec1 for y in vec2 -> x * y]

That's so incredibly succinct and clean. List comprehensions are a great tool in F# and I'm looking forward to learning more about the language as we move along.

Leave a Reply

Your email address will not be published. Required fields are marked *