F# Basics of functions


Most functions in F# are created with the let syntax:

let timesTwo x = x * 2

This defines a function named timesTwo that takes a single parameter x. If you run an interactive F# session (fsharpi on OS X and Linux, fsi.exe on Windows) and paste that function in (and add the ;; that tells fsharpi to evaluate the code you just typed), you'll see that it replies with:

val timesTwo : x:int -> int

This means that timesTwo is a function that takes a single parameter x of type int, and returns an int. Function signatures are often written without the parameter names, so you'll often see this function type written as int -> int.

But wait! How did F# know that x was an integer parameter, since you never specified its type? That's due to type inference. Because in the function body, you multiplied x by 2, the types of x and 2 must be the same. (As a general rule, F# will not implicitly cast values to different types; you must explicitly specify any typecasts you want).

If you want to create a function that doesn't take any parameters, this is the wrong way to do it:

let hello =  // This is a value, not a function
    printfn "Hello world"

The right way to do it is:

let hello () =
    printfn "Hello world"

This hello function has the type unit -> unit, which is explained in The "unit" type.