At my cur­rent con­tract, we’ve started a weekly brown bag ses­sion on F# and we’ve had two ses­sions so far, one on “what the hell are we doing” and a sec­ond on the basic syn­tax of the lan­guage. I pre­sented for the sec­ond one and hit most of the high points but some­thing I missed is that F# has list com­pre­hen­sions. Lots of times I find myself writ­ing C# code and wish­ing for the list com­pre­hen­sions 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 lit­tle cleaner but still kinda ugly:

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

At least the amount of code you are writ­ing is much less but it’s still not very clean.

But in F#, with list com­pre­hen­sions, you get this:

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

Wow, how freak­ing cool is that! Most of the suc­cinct­ness obvi­ously comes from F#‘s strong type infer­ence but in this day and age, why don’t all lan­guages have that?

List com­pre­hen­sions get even more inter­est­ing when you have mul­ti­ple lists that you want to work into a sin­gle list. For exam­ple, say you have two lists, each con­tain­ing vec­tors and you want a list of the prod­ucts of the vec­tors 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 incred­i­bly suc­cinct and clean. List com­pre­hen­sions are a great tool in F# and I’m look­ing for­ward to learn­ing more about the lan­guage as we move along.