Functions in F#

Functions are central in F#. We’ll learn about functions with a few different examples.

open System

// Here's a function that takes two integers and returns
// their sum as an integer.
let plus a b =
    a + b

// F# doesn't require explicit returns. The last expression
// in a function is automatically returned.

// When you have multiple parameters, you can separate them
// with spaces. The type is inferred, but can be explicitly specified.
let plusPlus (a: int) (b: int) (c: int) =
    a + b + c

[<EntryPoint>]
let main argv =
    // Call a function just as you'd expect, with name args.
    let res = plus 1 2
    printfn "1+2 = %d" res

    let res = plusPlus 1 2 3
    printfn "1+2+3 = %d" res

    0 // return an integer exit code

To run the program, save it as functions.fs and use the F# compiler:

$ dotnet fsi functions.fs
1+2 = 3
1+2+3 = 6

There are several other features to F# functions. One is pattern matching, which we’ll look at next.