[英]Match an Array in F#
I want to pattern match on the command line arguments array. 我想在命令行参数数组上进行模式匹配。
What I want to do is have a case that matches any case where there's at least one parameter or more and put that first parameter in a variable and then have another case that handles when there are no parameters. 我想要做的是有一个案例匹配任何至少有一个或多个参数的情况,并将第一个参数放在一个变量中,然后让另一个案例在没有参数时进行处理。
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
You can use truncate
: 你可以使用truncate
:
match args |> Array.truncate 1 with
| [| x |] -> x
| _ -> "No arguments"
The closest thing you'll get without converting to a list is: 在没有转换为列表的情况下,您最接近的是:
match argv with
| arr when argv.Length > 0 ->
let first = arr.[0]
printfn "%s" first
| _ -> printfn "none"
If you convert argv
to a list using Array.toList
, you can then pattern match on it as a list using the cons operator , ::
: 如果转换argv
使用到一个列表Array.toList
,然后你可以在它的模式匹配为使用列表利弊操作 , ::
:
match argv |> Array.toList with
| x::[] -> printfn "%s" x
| x::xs -> printfn "%s, plus %i more" x (xs |> Seq.length)
| _ -> printfn "nothing"
If you just want the first item, I prefer Array.tryHead
: 如果你只想要第一个项目,我更喜欢Array.tryHead
:
match Array.tryHead items with
| Some head -> printfn "%O" head
| None -> printfn "%s" "No items"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.