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
false
true
I need false in 3th call. How to get value or false
if key is not found? The problem is that TryGetValue
returns true
or false
depends on key
is found or not, but value is returned by reference.
It'll make your life easier if you define an Adapter for TryGetValue
that is more F#-like:
let tryGetValue k (d : Dictionary<_, _>) =
match d.TryGetValue k with
| true, v -> Some v
| _ -> None
With this, you can now define the buy
function like this:
let buy key limit =
price |> tryGetValue key |> Option.map ((>=) limit) |> Option.exists id
This gives you the desired result:
> buy "apple" 7;;
val it : bool = true
> buy "orange" 7;;
val it : bool = false
> buy "banana" 7;;
val it : bool = false
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