Paul Nikonowicz
Paul Nikonowicz

Reputation: 3903

Pattern matching with maps in F#

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?

Upvotes: 9

Views: 3451

Answers (1)

Daniel
Daniel

Reputation: 47904

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")]

Upvotes: 16

Related Questions