使用不完整的模式匹配作为过滤器

使用不完整的模式匹配作为过滤器

本文介绍了使用不完整的模式匹配作为过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

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

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

我可以在命令式for循环中使用不完整的模式匹配来过滤上面的列表:

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 = ()

但是会导致: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?

有没有一种方法可以使列表理解这项工作而不会导致MatchFailureException?例如像这样的东西:

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

推荐答案

两年前,您的代码是有效的,并且这是执行此操作的标准方法.然后,该语言已被清理,设计决定是使用显式语法.因此,我认为忽略警告不是一个好主意.

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)

对于另一个,List.sumBy非常合适:

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

这篇关于使用不完整的模式匹配作为过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 19:03