ZetCode

F# Result type

last modified December 2, 2026

In this article we handle errors with the Result type in F#.

A function that can fail needs a way to report the failure. The option type says that a value is missing, but not why. Result is a generic discriminated union of the standard library with two cases: Ok holds the result of a successful computation and Error holds a description of what went wrong.

type Result<'T, 'TError> =
    | Ok of ResultValue: 'T
    | Error of ErrorValue: 'TError

This is how Result is defined in FSharp.Core. The success value and the error value can have different types. The failure is part of the function's type, so the caller cannot overlook it.

Ok and Error

A function returns Ok or Error, and the caller matches on the two cases.

divide.fsx
let divide a b =
    if b = 0 then Error "division by zero"
    else Ok (a / b)

let show result =
    match result with
    | Ok value -> printfn "result: %d" value
    | Error msg -> printfn "error: %s" msg

show (divide 17 5)
show (divide 4 0)

The divide function has the type int -> int -> Result<int, string>. Both branches of the if must have the same type; Ok and Error are two cases of the same union, so they do.

λ dotnet fsi divide.fsx
result: 3
error: division by zero

Parsing input

Converting text to numbers is a typical operation that fails. The .NET method Int32.TryParse returns a tuple of a success flag and the parsed value, which we turn into a Result.

parse.fsx
open System

let parseInt (text: string) =
    match Int32.TryParse text with
    | true, n -> Ok n
    | false, _ -> Error $"'{text}' is not a number"

for input in ["42"; "-7"; "4x2"; ""] do
    match parseInt input with
    | Ok n -> printfn "parsed %d" n
    | Error msg -> printfn "error: %s" msg

The tuple pattern true, n matches when the parsing succeeds and binds the value; see F# tuples. Each error message contains the input that caused it.

λ dotnet fsi parse.fsx
parsed 42
parsed -7
error: '4x2' is not a number
error: '' is not a number

Errors as a union

A string is fine for a message, but the caller cannot react to different errors without parsing the text. A union of error cases describes every failure precisely.

error_union.fsx
open System

type AgeError =
    | NotANumber of string
    | Negative of int
    | TooHigh of int

let parseAge (text: string) =
    match Int32.TryParse text with
    | false, _ -> Error (NotANumber text)
    | true, n when n < 0 -> Error (Negative n)
    | true, n when n > 130 -> Error (TooHigh n)
    | true, n -> Ok n

let describe error =
    match error with
    | NotANumber s -> $"'{s}' is not a number"
    | Negative n -> $"{n} is negative"
    | TooHigh n -> $"{n} is too high"

for input in ["34"; "abc"; "-3"; "212"] do
    match parseAge input with
    | Ok age -> printfn "age %d" age
    | Error e -> printfn "%A: %s" e (describe e)

The result type is now Result<int, AgeError>.

| true, n when n < 0 -> Error (Negative n)

A guard with when adds a condition to a pattern. The rules are tried in order, so the last rule only sees valid ages.

let describe error =
    match error with
    | NotANumber s -> $"'{s}' is not a number"

The messages are produced in one place, separately from the checks. The compiler warns when a new error case is added and describe does not handle it.

λ dotnet fsi error_union.fsx
age 34
NotANumber "abc": 'abc' is not a number
Negative -3: -3 is negative
TooHigh 212: 212 is too high

Transforming results

Matching on every result gets repetitive. Result.map applies a function to an Ok value and passes an Error through unchanged; Result.mapError does the opposite.

map.fsx
open System

let parseInt (text: string) =
    match Int32.TryParse text with
    | true, n -> Ok n
    | false, _ -> Error text

let square x = x * x

printfn "%A" (parseInt "12" |> Result.map square)
printfn "%A" (parseInt "1z" |> Result.map square)

let toMessage text = $"cannot parse '{text}'"

printfn "%A" (parseInt "7" |> Result.map square |> Result.mapError toMessage)
printfn "%A" (parseInt "seven" |> Result.map square |> Result.mapError toMessage)

let celsius = parseInt "25" |> Result.map float |> Result.map (fun c -> c * 1.8 + 32.0)

match celsius with
| Ok f -> printfn "%.1f F" f
| Error e -> printfn "bad input: %s" e

The functions fit into pipelines.

printfn "%A" (parseInt "12" |> Result.map square)
printfn "%A" (parseInt "1z" |> Result.map square)

square knows nothing about errors. Result.map calls it for Ok 12 and skips it for an Error.

let celsius = parseInt "25" |> Result.map float |> Result.map (fun c -> c * 1.8 + 32.0)

Several map calls form a chain. The first one changes the type of the value from int to float.

λ dotnet fsi map.fsx
Ok 144
Error "1z"
Ok 49
Error "cannot parse 'seven'"
77.0 F

Chaining operations that fail

Result.map is for functions that always succeed. When the next step can fail as well, it returns a Result itself, and map would produce a nested Result<Result<...>>. Result.bind calls such a function and returns its result directly.

bind.fsx
open System

let parseInt (text: string) =
    match Int32.TryParse text with
    | true, n -> Ok n
    | false, _ -> Error $"'{text}' is not a number"

let positive n =
    if n > 0 then Ok n else Error $"{n} is not positive"

let even n =
    if n % 2 = 0 then Ok n else Error $"{n} is odd"

let half n = n / 2

let checkNumber text =
    parseInt text
    |> Result.bind positive
    |> Result.bind even
    |> Result.map half

for input in ["18"; "x"; "-4"; "7"] do
    printfn "%-4s %A" input (checkNumber input)

A number is parsed, checked to be positive and even, and halved.

let checkNumber text =
    parseInt text
    |> Result.bind positive
    |> Result.bind even
    |> Result.map half

Each step runs only when the previous one returned Ok. The first Error skips all remaining steps and becomes the result of the whole chain. The picture often used for this is a railway with two tracks: values travel on the success track, and a failure switches them to the error track for the rest of the way.

λ dotnet fsi bind.fsx
18   Ok 9
x    Error "'x' is not a number"
-4   Error "-4 is not positive"
7    Error "7 is odd"

Validating a record

A common use of Result is the validation of input. Each field is checked by its own function, and the checks are chained into one.

validation.fsx
type User = { Name: string; Age: int; Email: string }

type UserError =
    | EmptyName
    | InvalidAge of int
    | InvalidEmail of string

let checkName user =
    if user.Name.Trim() = "" then Error EmptyName else Ok user

let checkAge user =
    if user.Age < 0 || user.Age > 130 then Error (InvalidAge user.Age)
    else Ok user

let checkEmail user =
    if user.Email.Contains "@" then Ok user
    else Error (InvalidEmail user.Email)

let validate user =
    Ok user
    |> Result.bind checkName
    |> Result.bind checkAge
    |> Result.bind checkEmail

let users =
    [ { Name = "Lucia"; Age = 29; Email = "lucia@example.com" }
      { Name = " "; Age = 40; Email = "x@example.com" }
      { Name = "Tomas"; Age = 151; Email = "tomas@example.com" }
      { Name = "Eva"; Age = 35; Email = "eva.example.com" } ]

for user in users do
    match validate user with
    | Ok u -> printfn "valid: %s" u.Name
    | Error e -> printfn "invalid: %A" e

All check functions have the same shape: they take a user and return Ok with the same user or an Error.

let validate user =
    Ok user
    |> Result.bind checkName
    |> Result.bind checkAge
    |> Result.bind checkEmail

Starting the chain with Ok user makes all checks look alike. Adding a rule means writing one function and one more line. The chain stops at the first failed check, so each invalid user gets one error.

λ dotnet fsi validation.fsx
valid: Lucia
invalid: EmptyName
invalid: InvalidAge 151
invalid: InvalidEmail "eva.example.com"

Collecting results

When a function is applied to a list, we get a list of results. Often we want the successes and the failures separately.

collect.fsx
open System

let parseInt (text: string) =
    match Int32.TryParse text with
    | true, n -> Ok n
    | false, _ -> Error text

let inputs = ["10"; "x"; "25"; "7"; "eight"; "3"]
let results = List.map parseInt inputs

let numbers =
    results |> List.choose (fun r -> match r with Ok n -> Some n | Error _ -> None)

let errors =
    results |> List.choose (fun r -> match r with Error e -> Some e | Ok _ -> None)

printfn "numbers: %A, sum %d" numbers (List.sum numbers)
printfn "errors: %A" errors

let allOrNothing =
    if List.isEmpty errors then Ok numbers
    else Error $"{errors.Length} invalid values"

printfn "%A" allOrNothing

We parse a list of strings, keep the parsed numbers and the rejected inputs, and decide whether the whole input is valid.

results |> List.choose (fun r -> match r with Ok n -> Some n | Error _ -> None)

List.choose keeps the values for which the function returns Some. A short match on one line converts each result to an option.

let allOrNothing =
    if List.isEmpty errors then Ok numbers
    else Error $"{errors.Length} invalid values"

Some programs accept the valid part of the input, others reject everything when one value is wrong. Here the input is rejected, because two values are not numbers.

λ dotnet fsi collect.fsx
numbers: [10; 25; 7; 3], sum 45
errors: ["x"; "eight"]
Error "2 invalid values"

Default values and options

The Result module has a few helpers for the end of a chain, where a result is turned into a plain value or an option.

defaults.fsx
open System

let parseInt (text: string) =
    match Int32.TryParse text with
    | true, n -> Ok n
    | false, _ -> Error $"'{text}' is not a number"

let good = parseInt "64"
let bad = parseInt "sixty"

printfn "%b %b" (Result.isOk good) (Result.isError bad)
printfn "%d" (Result.defaultValue 0 good)
printfn "%d" (Result.defaultValue 0 bad)
printfn "%d" (Result.defaultWith (fun (e: string) -> e.Length) bad)
printfn "%A %A" (Result.toOption good) (Result.toOption bad)

isOk and isError test the case. defaultValue returns the Ok value or a default, and defaultWith computes the default from the error value; here it is the length of the error message. toOption keeps the value and drops the error, when the reason of a failure no longer matters.

λ dotnet fsi defaults.fsx
true true
64
0
23
Some 64 None

Source

F# language reference: Results

FSharp.Core: Result module

In this article we have returned Ok and Error values, described errors with unions, transformed results with map and mapError, chained validations with bind and collected results from lists. Unions are covered in F# discriminated unions and the option type in F# option type. Exceptions, the other way of reporting errors in .NET, are covered in F# exceptions.

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.