Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value or false by TryGetValue method

Tags:

dictionary

f#

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.

like image 936
Feofilakt Avatar asked Feb 01 '16 09:02

Feofilakt


1 Answers

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
like image 64
Mark Seemann Avatar answered Sep 23 '22 17:09

Mark Seemann