2016-02-01 10 views
5

Ho un dizionario e ottenere il valore:Valore restituito o falso con il metodo TryGetValue

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) 

vero

falsa

vero

ho bisogno di falso in 3 ° chiamata. Come ottenere il valore o false se la chiave non viene trovata? Il problema è che TryGetValue restituisce true o false dipende da key trovato o meno, ma il valore viene restituito per riferimento.

+0

il suggerimento è quello di cambiare 'snd |> (<) 'a qualcosa di un po 'più com, plicato –

risposta

7

Sarà rendere la vita più facile se si definisce un adattatore per TryGetValue che è più F # -come:

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

Con questo, si può ora definire la funzione buy in questo modo:

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

Questo ti dà il risultato desiderato:

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