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.

Advertisements

1 Response to “Your First F# Function”


  1. 1 Robert Pickering September 24, 2008 at 3:42 am

    Actually there’s some fairly clear guidance on this:-

    The form you should generally use is:
    let sqr x = x * x;;

    Use this form when you want pass a small function to another function (the sort of place where you’d use an anonymous method in C#):
    fun x -> x * x

    This form only when you really want to do pattern matching:
    let sqr = function
    | x -> x * x;;

    Cheers,
    Rob


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: