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
All you need to do is iterate over the pairs of key,val multiply each key*val then sum up the multiplied values and you get your correct total. And if you need just the number of matched, you can in another variable sum up just the vals .
You can create arrays in several ways. You can create a small array by listing consecutive values between [| and |] and separated by semicolons, as shown in the following examples. You can also put each element on a separate line, in which case the semicolon separator is optional.
Pattern matching is ubiquitous in F#. It is used for binding values to expressions with let , and in function parameters, and for branching using the match..with syntax.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With