map2

Namespace: FsToolkit.ErrorHandling

Function Signature

('a -> 'b -> 'c) -> Result<'a, 'd> -> Result<'b, 'd>
    -> Result<'c, 'd>

Examples

Note: Many use-cases requiring map operations can also be solved using the result computation expression.

Example 1

Let's assume that we have an add function that adds two numbers:

// int -> int -> int
let add a b = a + b

And an another function that converts a string to an integer:

// string -> Result<int, string>
let tryParseInt (str: string) =
  match System.Int32.TryParse str with
  | true, x -> Ok x
  | false, _ ->
    Error (sprintf "unable to parse '%s' to integer" str)

With the help of Result.map2 function, we can now do the following:

Example 2

Let's assume that we have the following types:

Latitude

Longitude

Location

Then, we can use the Result.map2 function as below to create the location with validation:

When we try with an invalid latitude value, we'll get the following result:

Last updated