F# 匹配F中的数组#

F# 匹配F中的数组#,f#,F#,我想在命令行参数数组上进行模式匹配 我想做的是让一个案例匹配至少有一个或多个参数的案例,并将第一个参数放入变量中,然后让另一个案例在没有参数时处理 match argv with | [| first |] -> // this only matches when there is one | [| first, _ |] -> // this only matches when there is two | [| first, tail |] -> /

我想在命令行参数数组上进行模式匹配

我想做的是让一个案例匹配至少有一个或多个参数的案例,并将第一个参数放入变量中,然后让另一个案例在没有参数时处理

match argv with
    | [| first |] -> // this only matches when there is one
    | [| first, _ |] -> // this only matches when there is two
    | [| first, tail |] -> // not working
    | argv.[first..] -> // this doesn't compile
    | [| first; .. |] -> // this neither
    | _ -> // the other cases

如果使用
Array.toList
argv
转换为列表,则可以使用,

match argv |> Array.toList with
    | x::[]  -> printfn "%s" x
    | x::xs  -> printfn "%s, plus %i more" x (xs |> Seq.length)
    | _  -> printfn "nothing"

在不转换为列表的情况下,最接近的结果是:

match argv with
| arr when argv.Length > 0 ->
    let first = arr.[0]
    printfn "%s" first
| _ -> printfn "none"
你可以:


如果您只需要第一项,我更喜欢
Array.tryHead

match Array.tryHead items with
| Some head -> printfn "%O" head
| None -> printfn "%s" "No items"

最简单的方法是转换为listOT,但如果您需要解析args方面的帮助,请查看优秀的Argu库,尝试使用数组进行转换将导致每次迭代的性能为O(n)(由于每次都会重新创建一个大小为-1的数组),而不是使用列表进行每次迭代的性能为O(1)。
match Array.tryHead items with
| Some head -> printfn "%O" head
| None -> printfn "%s" "No items"