【发布时间】:2011-04-11 22:10:49
【问题描述】:
假设我有以下代码:
type Vehicle =
| Car of string * int
| Bike of string
let xs = [ Car("family", 8); Bike("racing"); Car("sports", 2); Bike("chopper") ]
我可以在命令式 for 循环中使用不完整的模式匹配过滤上面的列表,例如:
> for Car(kind, _) in xs do
> printfn "found %s" kind;;
found family
found sports
val it : unit = ()
但会导致: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 的情况下使用列表理解?例如类似的东西:
> [for Car(_, seats) in xs -> seats] |> List.sum;;
val it : int = 10
【问题讨论】:
-
我认为该行应该是:[for Bus(_, seat) in xs -> seat] |> List.sum;;对? ;)
-
哦,我明白了! 2车! 5 x 2 = 10!主啊,帮助我。
-
这是一辆家用车和一辆跑车,所以 8 + 2 = 10。
标签: f# pattern-matching list-comprehension