我想在命令行参数数组上进行模式匹配.
我想要做的是有一个案例匹配任何至少有一个或多个参数的情况,并将第一个参数放在一个变量中,然后让另一个案例在没有参数时进行处理.
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
Run Code Online (Sandbox Code Playgroud)
如果使用 转换argv为列表Array.toList,则可以使用cons 运算符::,将其作为列表进行模式匹配:
match argv |> Array.toList with
| x::[] -> printfn "%s" x
| x::xs -> printfn "%s, plus %i more" x (xs |> Seq.length)
| _ -> printfn "nothing"
Run Code Online (Sandbox Code Playgroud)
你可以使用truncate:
match args |> Array.truncate 1 with
| [| x |] -> x
| _ -> "No arguments"
Run Code Online (Sandbox Code Playgroud)