Return value or false using the TryGetValue method

I have a dictionary and get the value:

open System.Collections.Generic let price = Dictionary<string, int>() Array.iter price.Add [|"apple", 5; "orange", 10|] let buy key = price.TryGetValue(key) |> snd |> (<) printfn "%A" (buy "apple" 7) printfn "%A" (buy "orange" 7) printfn "%A" (buy "banana" 7) 

True

falsely

True

I need false in the 3rd call. How to get a value or false if the key is not found? The problem is that TryGetValue returns true or false depends on key or not, but the value is returned by reference.

+5
source share
1 answer

This will simplify your life if you define an Adapter for TryGetValue , which is more like F #:

 let tryGetValue k (d : Dictionary<_, _>) = match d.TryGetValue k with | true, v -> Some v | _ -> None 

With this, you can now define the buy function as follows:

 let buy key limit = price |> tryGetValue key |> Option.map ((>=) limit) |> Option.exists id 

This gives the desired result:

 > buy "apple" 7;; val it : bool = true > buy "orange" 7;; val it : bool = false > buy "banana" 7;; val it : bool = false 
+7
source

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


All Articles