Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching with maps in F#

Tags:

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?

like image 313
Paul Nikonowicz Avatar asked Sep 18 '12 19:09

Paul Nikonowicz


1 Answers

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")]
like image 86
Daniel Avatar answered Oct 04 '22 14:10

Daniel