Search code examples
f#pattern-matchingdiscriminated-union

Matching a character to a discriminated union


I created a discriminated union which has three possible options:

type tool =
  | Hammer
  | Screwdriver
  | Nail

I would like to match a single character to one tool option. I wrote this function:

let getTool (letter: char) =
    match letter with
    | H -> Tool.Hammer
    | S -> Tool.Screwdriver
    | N -> Tool.Nail

Visual Studio Code throws me now the warning that only the first character will be matched and that the other rules never will be.

Can somebody please explain this behaviour and maybe provide an alternative?


Solution

  • That's not how characters are denoted in F#. What you wrote are variable names, not characters.

    To denote a character, use single quotes:

    let getTool (letter: char) =
        match letter with
        | 'H' -> Tool.Hammer
        | 'S' -> Tool.Screwdriver
        | 'N' -> Tool.Nail