Search code examples
f#inlinetype-constraints

Static constraint on Item


I'm trying to write a option-valued version of "TryGetValue" that will work on any object that implements either IDictionary or IReadOnlyDictionary. I have this :

let inline contains   (key:^key) (dictionary:^dic )=
    (^dic: (member ContainsKey: ^key -> bool) (dictionary, key) ) 

let inline tryGetValue (dictionary:^dic )  (key:^key)=
    if contains key dictionary then  
        let value = ( ^dic : (member  get_Item: ^key -> ^value )  (dictionary, key) )   (dictionary) ) key
        value |> Some
    else None  

The definition of "value" produces a warning that member constraints with name get_Item have special status which may cause runtime errors. What should I be doing here?


Solution

  • How about using TryGetValue instead of ContainsKey and Item?

    let inline tryGetValue dic key =
        let mutable value = Unchecked.defaultof< ^value>
        let contains = (^dic : (member TryGetValue : ^key * byref< ^value> -> bool) (dic, key, &value))
        if contains then Some value else None