Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Functions and Pipelines

Defining Functions in F#: Parameters, Types and Generics

Learn how to define F# functions with let, call them without parentheses, annotate types, return values, write generic and inline functions, use rec, and organise helper functions with nesting.

Functions are the main building block of F#. A function definition looks just like a value definition, with parameters after the name. There are no parentheses around arguments, no commas between them and no return keyword. Once you get used to it, the syntax feels light. This lesson covers definitions, calls, type signatures, nested helpers, generics and a few modifiers.

The shape of a function

FSHARP
let square x = x * x
let add a b = a + b
let greet name = $"Hello, {name}!"

Call a function by writing its name followed by its arguments, separated by spaces:

FSHARP
square 5          // 25
add 2 3           // 5
greet "Ada"       // "Hello, Ada!"

The result of the last expression is returned. For a function with several lines, indent the body:

FSHARP
let describe n =
    let doubled = n * 2
    let label = if doubled > 10 then "big" else "small"
    $"{n} doubled is {doubled} ({label})"

FSI answers a definition with the function's signature: val add: a: int -> b: int -> int. Read -> as "takes ... and gives": add takes an int and an int and gives an int. You will see precisely why the arrows chain this way in Currying and partial application.

Parentheses, grouping and precedence

Because arguments are separated by spaces, nested calls need parentheses to say what belongs together:

FSHARP
add (square 3) (square 4)       // 25
add square 3 square 4           // error: wrong arguments

Function application binds more tightly than operators. square 3 + 1 is (square 3) + 1, which is 10. And a negative argument needs care: add -1 2 can be read as subtraction, so write add (-1) 2.

Type annotations and return types

Inference usually figures out types. Annotate parameters with name: type inside parentheses, and the return type after all parameters:

FSHARP
let average (values: float list) : float =
    List.sum values / float (List.length values)

Why annotate? To document the contract, to guide the compiler where it cannot infer (for example, calling a method on a parameter) and to get better error messages. Public functions in a library should usually be annotated; small local helpers rarely need to be.

FSHARP
let shout (text: string) = text.ToUpper() + "!"    // needed: .ToUpper needs to know the type

Functions with no or one unit argument

A function with no meaningful input takes ():

FSHARP
let now () = System.DateTime.Now
let roll () = System.Random().Next(1, 7)

Without the (), let now = System.DateTime.Now would evaluate once and store a value. With it, the expression runs on every call.

Multi-argument styles: curried versus tupled

F# lets you write arguments in two ways:

FSHARP
let addCurried a b = a + b         // call: addCurried 2 3
let addTupled (a, b) = a + b       // call: addTupled (2, 3)

The curried style is the default for F# code because it allows partial application and pipelines. The tupled style resembles C# method calls and is how .NET methods are called: String.Join(", ", items). Use tupled arguments in public APIs that C# will call.

Nested functions

Functions can be defined inside functions to keep helpers private and to capture the outer parameters:

FSHARP
let formatPrice currency amount =
    let rounded = System.Math.Round(amount, 2)
    let symbol =
        match currency with
        | "USD" -> "$"
        | "EUR" -> "โ‚ฌ"
        | _ -> currency + " "
    $"{symbol}{rounded}"

Inner functions are also closures: they can use values from the enclosing scope.

FSHARP
let makeCounterLabel prefix =
    let label n = $"{prefix}-{n}"
    [ for i in 1 .. 3 -> label i ]
// makeCounterLabel "item" gives ["item-1"; "item-2"; "item-3"]

Generic functions

If a function does not depend on a concrete type, F# makes it generic automatically:

FSHARP
let swap (a, b) = (b, a)          // 'a * 'b -> 'b * 'a
let identity x = x                // 'a -> 'a
let first (x, _) = x              // 'a * 'b -> 'a

'a and 'b are type variables. swap (1, "x") and swap ("y", true) both work, with no casting. This is called automatic generalization, and it is why F# code is often short yet fully typed.

Arithmetic operators are a special case: let add a b = a + b is inferred as int -> int -> int, because the compiler chooses int for +. To make it work for any numeric type, use inline:

FSHARP
let inline addAny a b = a + b
addAny 1 2         // 3
addAny 1.5 2.5     // 4.0

inline copies the code into each call site and allows constraints on member operators, at the cost of bigger code. Use it for small numeric helpers.

Recursive functions

A function cannot call itself unless it is declared with rec. Recursion has its own lesson (Recursion); here is the shape:

FSHARP
let rec factorial n =
    if n <= 1 then 1 else n * factorial (n - 1)

Documentation and naming

Use verbs for actions (parseOrder, sendEmail) and nouns for pure computations (totalPrice). Add /// comments to public functions. Keep functions small: if you can name a part of the body, make it its own function.

Try it with C# stand-ins

C# expression-bodied methods look similar to the F# definitions above. These stand-ins exercise the same logic, including a generic swap.

C# C# stand-in: small functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# C# stand-in: a generic swap and recursion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you call a function add with arguments 2 and 3?

    Arguments are separated by spaces. add (2, 3) would pass one tuple argument instead.
  2. 2. What does a function return when it has several lines?

    F# has no return keyword; the last expression is the result.
  3. 3. What does let identity x = x have as its type?

    Nothing constrains x, so the function is generic over any type 'a.
  4. 4. Why write let now () = System.DateTime.Now with ()?

    Without the () you bind a value that is computed once.
  5. 5. Which keyword is needed for a function that calls itself?

    let rec lets the name be used inside its own body.

Summary

  • Define functions with let name parameters = body; call them with space-separated arguments.
  • The last expression is the result; signatures use arrows, such as int -> int -> int.
  • Annotate with (x: type) and : returnType when it helps; wrap nested calls in parentheses.
  • Use () for no-argument functions, nested functions for private helpers, and automatic generics for reuse.
  • inline generalizes numeric operators; rec enables recursion.

Next: Currying and partial application