Alexander Battisti
Alexander Battisti

Reputation: 2178

Using incomplete pattern matching as filter?

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

Upvotes: 5

Views: 1987

Answers (3)

pad
pad

Reputation: 41290

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

Upvotes: 5

Laurent
Laurent

Reputation: 2999

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

Upvotes: 10

Brian
Brian

Reputation: 118865

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).

Upvotes: 5

Related Questions