使用不完全模式匹配作为过滤器?

2024-01-18

假设我有以下代码:

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

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

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

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

由于忽略不匹配的元素是我的意图,是否有可能摆脱这个警告?

有没有一种方法可以使其与列表理解一起工作而不导致 Match FailureException?例如像这样的东西:

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

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

您的代码的标准替换是:

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

(您还可以使用焊盘示例中的高阶函数)

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

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

如果您更喜欢坚持使用推导式,那么这是显式语法:

[for x in xs do
    match x with
    | Car(_, seats) -> yield seats
    | _ -> ()
] |> List.sum
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用不完全模式匹配作为过滤器? 的相关文章

随机推荐