My First F# Experience

The following demonstration of F# was all performed in the interactive window installed with the F# add-in:

One of the interesting keywords I noticed in f# was the rec keyword.  This keyword allows you to do recursion.  To do recursion in C# or most other languages would be something like:

int factorial (int n)
{
   if (n ==  1)
     return 1;

   return factorial(n-1) * n;
}

in F# the equivalent looks like this:

let rec factorial n = if n>1 then
n * (n-1 |> factorial) else 1;;

Let's try to grok what it is saying here

let rec factorial n =

tells us we are defining a recursive function called factorial that takes one parameter n.  Note that we don't need to define int, F# figures it out!

if n > 1 then (n-1 |> factorial)

this statement says that if n is greater than one, call the factorial function with parameter n - 1.

n-1 |> factorial

is similar to the lambda ( =>)  in LINQ in that we are passing the parameter n - 1 back into the factorial function.

To call our F# function in the interactive window for 5!  we just say

factorial 5;;

This returns

val it : int = 120

if we want to subtract 5! - 3! we can type into the window:

factorial 5 - factorial 3;;

The result shows:

val it : int = 114

We can also define a function to do the subtraction by passing a tuple to the function called (x,y).  A tuple is a list of values that can be automatically typed for you by F#.  Below is our subtract function defined.

let subtract (x,y) = x - y;;

Passing the tuple (factorial 5, factorial 3) to our subtract function

subtract (factorial 5, factorial 3);;

returns

val it : int = 114

I know this looks like we are passing parameters, but we are really passing a tuple.  We can get the same result piping the tuple

(factorial 5, factorial 3)

to our subtract function:

(factorial 5, factorial 3) |> subtract;;

which returns the same result

val it : int = 114

It's a little confusing at first, but I think you'll find you get the hang of it after a while.  For algorithmic programming, life just got a lot simpler with F#.