Type classe, generic memoization

Posted by nicolas on Stack Overflow See other posts from Stack Overflow or by nicolas
Published on 2012-06-24T15:13:04Z Indexed on 2012/06/24 15:15 UTC
Read the original article Hit count: 254

Filed under:
|
|

Something quite odd is happening with y types and I quite dont understand if this is justified or not. I would tend to think not.

This code works fine :

   type DictionarySingleton private () = 
      static let mutable instance = Dictionary<string*obj, obj>()
      static member Instance = instance

   let  memoize  (f:'a -> 'b) = 
      fun (x:'a) ->
         let key = f.ToString(), (x :> obj)
         if (DictionarySingleton.Instance).ContainsKey(key) 
         then let r = (DictionarySingleton.Instance).[key]
              r :?> 'b
         else 
              let res = f x 
              (DictionarySingleton.Instance).[key] <- (res :> obj)
              res

And this ones complains

   type DictionarySingleton private () = 
      static let mutable instance = Dictionary<string*obj, _>()
      static member Instance = instance

   let  memoize  (f:'a -> 'b) = 
      fun (x:'a) ->
         let key = f.ToString(), (x :> obj)
         if (DictionarySingleton.Instance).ContainsKey(key) 
         then let r = (DictionarySingleton.Instance).[key]
              r :?> 'b
         else 
              let res = f x 
              (DictionarySingleton.Instance).[key] <- (res :> obj)
              res

The difference is only the underscore in the dictionary definition. The infered types are the same, but the dynamic cast from r to type 'b exhibits an error.

'this runtime coercition ... runtime type tests are not allowed on some types, etc..'

Am I missing something or is it a rough edge ?

© Stack Overflow or respective owner

Related posts about compiler

Related posts about F#