相关疑难解决方法(0)

使用不完整模式匹配作为过滤器

假设我有以下代码:

type Vehicle =
| Car  of string * int
| Bike of string

let xs = [ Car("family", 8); Bike("racing"); Car("sports", 2); Bike("chopper") ]
Run Code Online (Sandbox Code Playgroud)

我可以使用不完整的模式匹配过滤上面的列表,如下所示:

> for Car(kind, _) in xs do
>    printfn "found %s" kind;;

found family
found sports
val it : unit = ()
Run Code Online (Sandbox Code Playgroud)

但它会导致:warning FS0025: Incomplete pattern matches on this expression. For example, the value 'Bike (_)' may indicate a case not covered by the pattern(s). Unmatched elements will be ignored.

由于忽略了无与伦比的元素是我的意图,是否有可能摆脱这种警告?

是否有一种方法可以使列表推导工作,而不会导致MatchFailureException?例如:

> …
Run Code Online (Sandbox Code Playgroud)

f# list-comprehension pattern-matching

5
推荐指数
3
解决办法
1843
查看次数

标签 统计

f# ×1

list-comprehension ×1

pattern-matching ×1