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.

2 thoughts on “List Comprehensions in F#

  1. The code: let products = [for x in vec1 for y in vec2 -> x * y] is not even syntactically correct (it needs a do after vec1). But it will not do what is intended anyway. This blog is a waste of time. Your scotch driven rants are worthless. This code speaks to the quality of your thought.

  2. At the risk of replying to an angry, idiotic troll, here goes:

    John, try looking at the date of this post and compare it to when F# was released. The syntax is perfectly valid and in fact executes. However, the construct has been deprecated in a later release in favor of the do-yield construct you halfway manage to mention. The code does exactly what is intended which is produces a list with the products of each item in the two lists.

    Try using your energy to improve and understand the world instead of being an ass.

Leave a Reply

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