F# pattern match directly against let binding

前端 未结 4 454
不知归路
不知归路 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 23:13

    You can only use literals if you want to match against a particular value in a pattern matching case. An identifier means binding -- i.e. the actual value in this pattern matching case will be bound to the identifier that will be visible in the scope of this case.

    As @DanielFabian has shown, you can define your own literals and give them names.

    If the value you need to match against isn't known at compile time, you can use guards like so:

    match arg with
    | x when x = key1 -> "value1"
    | x when x = key2 -> "value2"
    | _ -> // etc
    

    See the MSDN article on pattern matching for more details.

提交回复
热议问题