F#模式直接针对let绑定进行匹配 [英] F# pattern match directly against let binding
本文介绍了F#模式直接针对let绑定进行匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在F#中是否可以直接对let绑定进行模式匹配?
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"
以下内容针对匹配key2
和_
的行给出警告此规则将永远不会匹配" :
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"
这是因为尽管它们是不可变的,但let绑定却不同于C#const
变量?
Is this because although they're immutable, the let bindings are unlike C# const
variables?
推荐答案
只需使用大写字母并[<Literal>]
即可,它会按预期工作.
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.
这篇关于F#模式直接针对let绑定进行匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文