Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 431
Alexander Battisti Avatar asked Apr 11 '11 22:04

Alexander Battisti


2 Answers

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
like image 114
Laurent Avatar answered Nov 01 '22 06:11

Laurent


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

like image 23
Brian Avatar answered Nov 01 '22 08:11

Brian