Matching patterns with cards in F #

Given the map:

let myMap = Map.ofArray [| (1,"A");(2,"B") |] 

Is there a way to use pattern matching similar to cons list operator?

Something like that:

 match myMap with //doesn't work (1, value) -> () | _ -> () 

Or:

 match myMap with //doesn't work 1::value -> () | _ -> () 

What I do not want to do is:

 match myMap.TryFind(1) with //boring Some value -> () | _ -> () 

How can I map an image to a map?

+6
source share
1 answer

As you noted, TryFind is a standard approach, and I cannot come up with a compelling reason to wrap it with an active template for simple key verification. However, if you are planning on something like restructuring the list (for example, returning the found value and the rest 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")] 
+13
source

Source: https://habr.com/ru/post/925711/


All Articles