Using incomplete pattern matching as filter?

余生颓废 提交于 2019-12-07 04:56:17

问题


Suppose I have the following code:

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

let xs = [ Car("family", 8); Bike("racing"); Car("sports", 2); Bike("chopper") ]

I can filter above list using incomplete pattern matching in an imperative for loop like:

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

found family
found sports
val it : unit = ()

but it will cause a: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.

As the ignoring of unmatched elements is my intention, is there a possibility to get rid of this warning?

And is there a way to make this work with list-comprehensions without causing a MatchFailureException? e.g. something like that:

> [for Car(_, seats) in xs -> seats] |> List.sum;;
val it : int = 10

回答1:


Two years ago, your code was valid and it was the standard way to do it. Then, the language has been cleaned up and the design decision was to favour the explicit syntax. For this reason, I think it's not a good idea to ignore the warning.

The standard replacement for your code is:

for x in xs do
    match x with
    | Car(kind, _) -> printfn "found %s" kind
    | _ -> ()

(you could also use high-order functions has in pad sample)

For the other one, List.sumBy would fit well:

xs |> List.sumBy (function Car(_, seats) -> seats | _ -> 0)

If you prefer to stick with comprehensions, this is the explicit syntax:

[for x in xs do
    match x with
    | Car(_, seats) -> yield seats
    | _ -> ()
] |> List.sum



回答2:


You can silence any warning via the #nowarn directive or --nowarn: compiler option (pass the warning number, here 25 as in FS0025).

But more generally, no, the best thing is to explicitly filter, as in the other answer (e.g. with choose).




回答3:


To explicitly state that you want to ignore unmatched cases, you can use List.choose and return None for those unmatched elements. Your codes could be written in a more idomatic way as follows:

let _ = xs |> List.choose (function | Car(kind, _) -> Some kind
                                    | _ -> None)
           |> List.iter (printfn "found %s")

let sum = xs |> List.choose (function | Car(_, seats)-> Some seats
                                      | _ -> None) 
             |> List.sum


来源:https://stackoverflow.com/questions/5628151/using-incomplete-pattern-matching-as-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!