user6347904
user6347904

Reputation:

Get multiple pattern matches

I have the following list of tuples (ie note the ; and ,):

let nodes = [0, 1, 394; 0, 2, 4; 1, 3, 50; 1, 2, 5; 2, 3, 600]

I want to find all tuples in the list that have the first element = 0, so I do the following pattern match:

match nodes with
| [_; 0, a, b; _] | [_; 0, a, b] | [0, a, b; _] -> doStuff a b  //a tuple of the form (0, _, _) was found in the list 
| _ -> doOtherStuff //no matches found

There are a couple of problems with this that I'm unable to fix:

  1. I only get the a & b of one of the matched tuples, any other matches are ignored
  2. I had to look for three cases (tuple in the middle, start, and end of list), which is pretty verbose IMO

Any way to fix these problems? (is there a way to get multiple matches, and to match regardless of the position of the tuple within the list?)

Upvotes: 0

Views: 283

Answers (1)

Sehnsucht
Sehnsucht

Reputation: 5049

Each tuple is one element of the list, so if you want all elements where first "part" is 0, just filter your list with that predicate

nodes
|> List.filter (fun (x, _, _) -> x = 0)
|> List.map (fun (_, a, b) -> doStuff a b)

Alternatively if there is something to do in each case (where first part is 0 and when not) you can directly do your mapping with a pattern match inside

nodes
|> List.map (function (0, a, b) -> doStuff a b)
                    | _         -> doOtherStuff)

Upvotes: 3

Related Questions