Lastwall
Lastwall

Reputation: 239

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

Upvotes: 13

Views: 5088

Answers (4)

sdgfsdh
sdgfsdh

Reputation: 37045

If you just want the first item, I prefer Array.tryHead:

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

Upvotes: 5

Mark Seemann
Mark Seemann

Reputation: 233135

You can use truncate:

match args |> Array.truncate 1 with
| [| x |] -> x
| _       -> "No arguments"

Upvotes: 10

Asik
Asik

Reputation: 22133

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"

Upvotes: 4

Squimmy
Squimmy

Reputation: 587

If you convert argv to a list using Array.toList, you can then pattern match on it as a list using the cons operator, :::

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

Upvotes: 9

Related Questions