An Experiment in Scotch

"I write to discover what I believe." Michael Lopp on Twitter

List Comprehensions in F#

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.


  1. The code: let prod­ucts = [for x in vec1 for y in vec2 -> x * y] is not even syn­tac­ti­cally cor­rect (it needs a do after vec1). But it will not do what is intended any­way. This blog is a waste of time. Your scotch dri­ven rants are worth­less. This code speaks to the qual­ity of your thought.

  2. Scotch Drinker

    December 16, 2009 at 11:50 am

    At the risk of reply­ing to an angry, idi­otic troll, here goes:

    John, try look­ing at the date of this post and com­pare it to when F# was released. The syn­tax is per­fectly valid and in fact exe­cutes. How­ever, the con­struct has been dep­re­cated in a later release in favor of the do-yield con­struct you halfway man­age to men­tion. The code does exactly what is intended which is pro­duces a list with the prod­ucts of each item in the two lists.

    Try using your energy to improve and under­stand the world instead of being an ass.

Leave a Reply

Your email address will not be published.