我有一本字典并获得价值:
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)
Run Code Online (Sandbox Code Playgroud)
真正
假
真正
我在第3次电话中需要假.如何获得价值或未false找到钥匙?问题是是否找到了TryGetValue返回true或false依赖key,但是通过引用返回值.
如果你定义一个TryGetValue更像F#的适配器,它会让你的生活更轻松:
let tryGetValue k (d : Dictionary<_, _>) =
match d.TryGetValue k with
| true, v -> Some v
| _ -> None
Run Code Online (Sandbox Code Playgroud)
有了这个,您现在可以buy像这样定义函数:
let buy key limit =
price |> tryGetValue key |> Option.map ((>=) limit) |> Option.exists id
Run Code Online (Sandbox Code Playgroud)
这会给你想要的结果:
> buy "apple" 7;;
val it : bool = true
> buy "orange" 7;;
val it : bool = false
> buy "banana" 7;;
val it : bool = false
Run Code Online (Sandbox Code Playgroud)