Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match an Array in F#

Tags:

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
like image 526
Lastwall Avatar asked Feb 23 '16 02:02

Lastwall


People also ask

How do you match numbers in an array?

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 .

How to define an array in f#?

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.

What is pattern matching in F#?

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.


1 Answers

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"
like image 155
Squimmy Avatar answered Nov 10 '22 02:11

Squimmy