Given the map:
let myMap = Map.ofArray [| (1,"A");(2,"B") |]
Is there a way i can use pattern matching similiar to a list cons operator?
Something like this:
match myMap with //doesn't work
(1, value) -> ()
| _ -> ()
Or:
match myMap with //doesn't work
1::value -> ()
| _ -> ()
What i don't want to do is this:
match myMap.TryFind(1) with //boring
Some value -> ()
| _ -> ()
How can I do pattern matching with a map?
As you noted, matching over TryFind
is the standard approach and I can't think of a compelling reason to wrap it with an active pattern for a simple key check. However, if you're going for something like list destructuring (i.e. return the found value and the remainder of the map) this should work:
let (|Found|_|) key map =
map
|> Map.tryFind key
|> Option.map (fun x -> x, Map.remove key map)
let map = Map.ofList [1, "A"; 2, "B"]
match map with
| Found 1 (x, rest) -> printfn "Value: %A, Remaining: %A" x rest
| _ -> ()
//prints: Value: "A", Remaining: map [(2, "B")]
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