Search code examples
f#pattern-matchingimmutabilityguard-clause

F# pattern match directly against let binding


Is it possible in F# to pattern match directly against a let binding?

For example, this compiles without any warnings:

    let value = 
        match arg with
        | 1 -> "value1"
        | 2 -> "value2"
        | _ -> failwith "key not found"

Whereas the following gives the warning "This rule will never be matched" against the lines matching key2 and _:

    let key1 = 1
    let key2 = 2
    let value = 
        match arg with
        | key1 -> "value1"
        | key2 -> "value2"
        | _ -> failwith "key not found"

Is this because although they're immutable, the let bindings are unlike C# const variables?


Solution

  • just use capital letters and [<Literal>] them and it works as expected.

    let [<Literal>] X = 0
    let [<Literal>] Y = 1
    let bla arg =
        match arg with
        | X -> "zero"
        | Y -> "one"
        | somethingelse -> somethingelse.ToString()
    

    the lower case name by convention typically means a wildcard that is bound to the name.