假設我有以下代碼:使用不完整的模式匹配作爲過濾器?
type Vehicle =
| Car of string * int
| Bike of string
let xs = [ Car("family", 8); Bike("racing"); Car("sports", 2); Bike("chopper") ]
我可以使用不完整的圖案匹配過濾器上方列表中的當務之急樣環:
> 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
我認爲這條線假設是:[公共汽車(_,座位)在xs - >席位] |> List.sum ;;對? ;) – 2011-04-11 23:52:01
哦,我明白了! 2輛車! 5 x 2 = 10!主啊,幫助我。 – 2011-04-12 00:03:27
這是一輛家庭轎車和一輛跑車,所以8 + 2 = 10。 – Laurent 2011-04-12 00:05:27