ZetCode

F# functions

last modified December 2, 2026

In this article we define and call functions in F#.

A function is a named piece of code that takes arguments and returns a result. Functions are the main building block of F# programs. They are defined with the same let keyword as values, and they are values themselves: a function can be bound to a name, passed to another function, or returned from one.

Defining a function

A function definition is a let binding with parameters between the name and the equals sign. The expression after the equals sign is the body; its value is the result of the function.

square.fsx
let square x = x * x

let a = square 5
let b = square 12

printfn "square 5 = %d" a
printfn "square 12 = %d" b
printfn "square 3 + 1 = %d" (square 3 + 1)
printfn "square (3 + 1) = %d" (square (3 + 1))

We define a function that squares its argument and call it a few times.

let square x = x * x

The function has one parameter, x. There is no return keyword: the function returns the value of its body.

let a = square 5

A function is called by writing the argument after its name, separated by a space.

printfn "square 3 + 1 = %d" (square 3 + 1)
printfn "square (3 + 1) = %d" (square (3 + 1))

Function application binds more tightly than any operator. square 3 + 1 is (square 3) + 1; to square the sum, we put it in parentheses.

λ dotnet fsi square.fsx
square 5 = 25
square 12 = 144
square 3 + 1 = 10
square (3 + 1) = 16

Several parameters

The parameters of a function are separated by spaces, both in the definition and in the call.

parameters.fsx
let add x y = x + y

let rectArea width height = width * height

let describe name age =
    printfn "%s is %d years old" name age

printfn "add 3 4 = %d" (add 3 4)
printfn "area 5 8 = %d" (rectArea 5 8)
printfn "nested: %d" (add (rectArea 2 3) (add 1 1))

describe "Lucia" 34
describe "Tomas" 27

We define three functions with two parameters each.

printfn "nested: %d" (add (rectArea 2 3) (add 1 1))

When an argument is itself a function call, it must be in parentheses. Without them, add rectArea 2 3 ... would pass rectArea as the first argument.

let describe name age =
    printfn "%s is %d years old" name age

The body may start on the next line, indented. The compiler infers from the format string that name is a string and age an int.

λ dotnet fsi parameters.fsx
add 3 4 = 7
area 5 8 = 40
nested: 8
Lucia is 34 years old
Tomas is 27 years old

Type annotations

The compiler infers the types of parameters from the way the body uses them. When it cannot, or when we want to state the types explicitly, we annotate the parameters.

annotations.fsx
let half x = x / 2
let halfF (x: float) = x / 2.0

let average (a: float) (b: float) : float =
    (a + b) / 2.0

let initials (first: string) (last: string) =
    string first[0] + "." + string last[0] + "."

let shout (s: string) = s.ToUpper() + "!"

printfn "half 7 = %d" (half 7)
printfn "halfF 7.0 = %.1f" (halfF 7.0)
printfn "average = %.2f" (average 4.0 7.5)
printfn "initials = %s" (initials "Lucia" "Novak")
printfn "%s" (shout "hello there")

The program defines functions on integers, floats and strings.

let half x = x / 2
let halfF (x: float) = x / 2.0

Since 2 is an int, the parameter of half is an int as well. An annotated parameter is written in parentheses: (x: float).

let average (a: float) (b: float) : float =
    (a + b) / 2.0

The return type is written after the parameters, separated by a colon.

let shout (s: string) = s.ToUpper() + "!"

Here the annotation is required. To find the ToUpper method, the compiler must know the type of s before it reaches the method call; without the annotation, the program does not compile.

λ dotnet fsi annotations.fsx
half 7 = 3
halfF 7.0 = 3.5
average = 5.75
initials = L.N.
HELLO THERE!

Function types

A function has a type like any other value. F# writes it with arrows: the types of the parameters, then the type of the result. We can see the types in F# Interactive.

In the session below, multiply has the type int -> int -> int: it takes two integers and returns an integer. A function that returns nothing useful, like greet, returns unit. The type of timesTwo is explained in the section on partial application.

λ dotnet fsi

> let multiply x y = x * y;;
val multiply: x: int -> y: int -> int

> let average (a: float) (b: float) = (a + b) / 2.0;;
val average: a: float -> b: float -> float

> let greet name = printfn "Hello there, %s!" name;;
val greet: name: string -> unit

> let timesTwo = multiply 2;;
val timesTwo: (int -> int)

Local values in the body

A body may span several lines. It can bind local values with let; the last expression is the result.

body.fsx
let bmi (weight: float) (height: float) =
    let heightM = height / 100.0
    let value = weight / (heightM * heightM)
    round (value * 10.0) / 10.0

let category (value: float) =
    if value < 18.5 then "underweight"
    elif value < 25.0 then "normal"
    elif value < 30.0 then "overweight"
    else "obese"

let report name weight height =
    let value = bmi weight height
    let cat = category value
    printfn "%-6s %5.1f kg %5.1f cm  BMI %4.1f  %s" name weight height value cat

report "Lucia" 58.0 167.0
report "Tomas" 92.5 181.0
report "Erik" 54.0 183.0
report "Anna" 74.0 165.0

We compute the body mass index of four people and put it into a category.

let bmi (weight: float) (height: float) =
    let heightM = height / 100.0
    let value = weight / (heightM * heightM)
    round (value * 10.0) / 10.0

The local values heightM and value exist only inside the function. The last line, which rounds the value to one decimal place, is the result.

let category (value: float) =
    if value < 18.5 then "underweight"
    elif value < 25.0 then "normal"
    elif value < 30.0 then "overweight"
    else "obese"

The body of category is a single if expression, and each branch returns a string; see F# conditionals.

printfn "%-6s %5.1f kg %5.1f cm  BMI %4.1f  %s" name weight height value cat

The report function calls the other two. A function can only call functions defined above it. In the format string, %-6s left-aligns the name in six columns and %5.1f right-aligns a float in five.

λ dotnet fsi body.fsx
Lucia   58.0 kg 167.0 cm  BMI 20.8  normal
Tomas   92.5 kg 181.0 cm  BMI 28.2  overweight
Erik    54.0 kg 183.0 cm  BMI 16.1  underweight
Anna    74.0 kg 165.0 cm  BMI 27.2  overweight

Functions without a result

A function called for its side effect, such as printing, returns unit, whose only value is written (). A function without parameters takes () as its argument.

unit_functions.fsx
let separator () =
    printfn "------------------"

let greet name =
    printfn "Hello there, %s!" name

let header title =
    separator ()
    printfn "%s" title
    separator ()

header "Guests"
greet "Lucia"
greet "Tomas"
separator ()

let result = greet "Erik"
printfn "result: %A" result

We print a short guest list with helper functions.

let separator () =
    printfn "------------------"

The empty parentheses make separator a function. Without them, let separator = printfn "..." would be a value: the line would be printed once, when the binding is evaluated, and separator would just hold ().

let header title =
    separator ()
    printfn "%s" title
    separator ()

Lines of a body that return unit are executed in order. The call separator () passes the unit value as the argument.

let result = greet "Erik"
printfn "result: %A" result

The result of greet is the unit value, printed by %A as (). The unit type has an article of its own: F# unit type.

λ dotnet fsi unit_functions.fsx
------------------
Guests
------------------
Hello there, Lucia!
Hello there, Tomas!
------------------
Hello there, Erik!
result: ()

Matching on arguments

A function body is often a match expression on a parameter. F# has a shorter form for this: the function keyword defines a function whose single parameter is matched directly.

matching.fsx
let dayName day =
    match day with
    | 1 -> "Monday"
    | 2 -> "Tuesday"
    | 3 -> "Wednesday"
    | 4 -> "Thursday"
    | 5 -> "Friday"
    | 6 | 7 -> "weekend"
    | _ -> "invalid day"

let signName n =
    match n with
    | 0 -> "zero"
    | x when x > 0 -> "positive"
    | _ -> "negative"

let grade = function
    | s when s >= 90 -> 'A'
    | s when s >= 75 -> 'B'
    | s when s >= 60 -> 'C'
    | _ -> 'F'

for d in [3; 6; 9] do
    printfn "%d: %s" d (dayName d)

for n in [-4; 0; 12] do
    printfn "%d is %s" n (signName n)

for s in [95; 78; 61; 40] do
    printfn "score %d: grade %c" s (grade s)

We define three functions that turn numbers into names, signs and grades.

let dayName day =
    match day with
    | 1 -> "Monday"
    ...
    | 6 | 7 -> "weekend"
    | _ -> "invalid day"

The result of the function is the result of the matching branch. The wildcard _ handles all other numbers.

let grade = function
    | s when s >= 90 -> 'A'
    | s when s >= 75 -> 'B'
    | s when s >= 60 -> 'C'
    | _ -> 'F'

With function, the parameter has no name; each pattern binds the argument itself. The when guards add conditions to the patterns. Matching is covered in F# match expression.

λ dotnet fsi matching.fsx
3: Wednesday
6: weekend
9: invalid day
-4 is negative
0 is zero
12 is positive
score 95: grade A
score 78: grade B
score 61: grade C
score 40: grade F

Partial application

An F# function with several parameters is in fact a chain of functions that take one argument each. The type int -> int -> int reads as int -> (int -> int): a function that takes an integer and returns a function from integer to integer. This is called currying. Calling the function with fewer arguments than it has parameters returns a new function that waits for the rest; this is partial application.

partial.fsx
let multiply x y = x * y

let timesTwo = multiply 2
let timesThree = multiply 3

printfn "timesTwo 7 = %d" (timesTwo 7)
printfn "timesThree 7 = %d" (timesThree 7)

let price rate amount = amount + amount * rate

let withVat = price 0.20
let withReducedVat = price 0.10

printfn "%.2f" (withVat 50.0)
printfn "%.2f" (withReducedVat 50.0)

let greet greeting name = printfn "%s, %s!" greeting name

let hello = greet "Hello there"
let goodbye = greet "Goodbye"

hello "Lucia"
goodbye "Lucia"

We create specialized functions from general ones.

let multiply x y = x * y

let timesTwo = multiply 2
let timesThree = multiply 3

timesTwo is multiply with x fixed to 2; it takes the remaining argument y.

let price rate amount = amount + amount * rate

let withVat = price 0.20

Partial application fixes the parameters from the left. That is why functions usually take their configuration first and the data last: rate comes before amount.

let hello = greet "Hello there"

Functions that print can be partially applied too.

λ dotnet fsi partial.fsx
timesTwo 7 = 14
timesThree 7 = 21
60.00
55.00
Hello there, Lucia!
Goodbye, Lucia!

Functions as values

Functions can be passed as arguments and returned as results. A function that takes or returns another function is a higher-order function.

higher_order.fsx
let square x = x * x
let increment x = x + 1
let negate x = -x

let applyTwice f x = f (f x)

let applyAll f a b c =
    printfn "%d %d %d" (f a) (f b) (f c)

printfn "applyTwice square 3 = %d" (applyTwice square 3)
printfn "applyTwice increment 3 = %d" (applyTwice increment 3)

applyAll square 1 2 3
applyAll negate 1 2 3

let choose useSquare =
    if useSquare then square else increment

let f = choose true
let g = choose false

printfn "f 9 = %d, g 9 = %d" (f 9) (g 9)

We pass named functions to other functions and choose a function at run time.

let applyTwice f x = f (f x)

The parameter f is a function; applyTwice calls it twice. The compiler infers that f must take and return a value of the type of x.

let choose useSquare =
    if useSquare then square else increment

choose returns one of two functions. Both branches of the if have the same type, int -> int. Functions without a name are covered in F# lambda.

λ dotnet fsi higher_order.fsx
applyTwice square 3 = 81
applyTwice increment 3 = 5
1 4 9
-1 -2 -3
f 9 = 81, g 9 = 10

Calling .NET methods

.NET methods are called differently from F# functions: the arguments are put in parentheses and separated by commas. F# code freely mixes both.

methods.fsx
let larger = System.Math.Max(3, 9)
let rounded = System.Math.Round(2.567, 2)
let padded = "7".PadLeft(3, '0')

printfn "%d" larger
printfn "%.2f" rounded
printfn "%s" padded

let hypotenuse a b =
    System.Math.Sqrt(a * a + b * b)

let label (name: string) width =
    name.ToUpper().PadRight(width, '.')

printfn "%.2f" (hypotenuse 3.0 4.0)
printfn "%s%d" (label "apples" 10) 12
printfn "%s%d" (label "kiwis" 10) 7

We call methods of the Math and String classes and use them in F# functions.

let larger = System.Math.Max(3, 9)
let padded = "7".PadLeft(3, '0')

Math.Max is a static method, called on the class. PadLeft is called on a string value; it pads the string with zeros to three characters.

let label (name: string) width =
    name.ToUpper().PadRight(width, '.')

An F# function can call .NET methods in its body. As in the shout function, the method call needs the annotation of name. Method calls can be chained.

λ dotnet fsi methods.fsx
9
2.57
007
5.00
APPLES....12
KIWIS.....7

Source

F# language reference: Functions

F# language reference: let Bindings

In this article we have defined F# functions, annotated their parameters, looked at their types, and used currying, partial application and higher-order functions. Anonymous functions are covered in F# lambda, chaining functions in F# pipelines and composition, and functions that call themselves in F# recursion.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.