Your First F# Function

F# functions are weird. OK, that’s the C# programmer in me speaking. I’m going to make a point of writing up F# fundamentals over the next month to (a) help me understand what’s going on; and (b) to help you, the Searcher Brought By The Google, to understand if you search for something like “first f# function”.

So: function declarations. You can do them several ways. First, the direct way:

let sqr x = x * x;;

This declares a function sqr that takes a single parameter x, and returns the square. Simple? Maybe. There’s a lot going on.

Functions are declared the same way that normal variables are, using the let statement.

You don’t need to declare types. F# will infer the types for you. In this case, it will assume x is an integer value, since you’re multiplying it in the body of the function.

Further, there are alternate ways to declare the same function. Here’s one, from F# for Scientists, by Dr. Jon D. Harrop (p. 13):

let sqr = fun x -> x * x;;

This one says, assign the sqr variable to an anonymous function that takes a single parameter x and returns the square of x. This shows even more clearly that functions are first-class citizens in F#.

How about this one?

let sqr = function

| x -> x * x;;

This uses F#’s pattern-matching syntax.

So, there are several ways to skin that particular cat. Which one is best? F# seems to encourage terseness, so I would keep that in mind.