phoog
phoog

Reputation: 43046

Pattern matching with type annotations

At https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching#tuple-pattern, there is this example of a pattern with a type annotation:

Patterns can have type annotations. These behave like other type annotations and guide inference like other type annotations. Parentheses are required around type annotations in patterns. The following code shows a pattern that has a type annotation.

let detect1 x =
      match x with
      | 1 -> printfn "Found a 1!"
      | (var1 : int) -> printfn "%d" var1
  detect1 0
  detect1 1

The type annotation (var1 : int) is redundant because the literal 1 in the previous pattern establishes the type unambiguously.

Is there any case in which a type annotation such as this would be useful?

Upvotes: 5

Views: 231

Answers (1)

Nghia Bui
Nghia Bui

Reputation: 3784

Actually, even when you use type annotation in function parameters, you are using type annotation in patterns too. F# pattern matching works even on function parameters (let binding in general).

So, as usual, type annotation is useful when we want to enforce the type immediately instead of relying on the type inference. We can have many places to put type annotation to achieve the same result. Just choose the place that is most convenient for the situation. Consider example below:

let detect2 (x : int option) =
    match x with
    | Some y -> ...
    | None -> ...

We can write shorter:

let detect2 x =
    match x with
    | Some (y : int)
    | None -> ...

In this situation we should prefer the later one.

Upvotes: 2

Related Questions