F# pattern match directly against let binding

前端 未结 4 453
不知归路
不知归路 2021-01-18 22:39

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

For example, this compiles without any warnings:

    let value = 
        match         


        
4条回答
  •  暖寄归人
    2021-01-18 22:58

    There are two main issues raised by the code you are trying to use.

    Firstly pattern matching:

    match arg with
    | _ -> "value"
    

    matches arg with anything and then returns "value"

    match arg with
    | a -> "value"
    

    matches arg with anything, calls it "a", and then returns "value". You can think of the match having it's own little namespace, the a only exists in the match, and the match only 'sees' the things that have been named in it.

    Secondly, if you want to match to a set of predefined values, then you probably want to use discriminated unions. You can define one like this:

    type Keys=
    | Key1
    | Key2
    

    Then match like this:

    match arg with
    | Key1 -> "value1"
    | Key2 -> "value2"
    

    In this case it matches against the type Keys, not a value called Key1 or Key2.

提交回复
热议问题