1

y 类型发生了一些非常奇怪的事情,我很不明白这是否合理。我倾向于认为不是。

此代码工作正常:

   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

而这个抱怨

   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

区别只是字典定义中的下划线。推断的类型是相同的,但是从 r 到类型 'b 的动态转换会出现错误。

'这个运行时强制......运行时类型测试在某些类型上是不允许的,等等......'

我错过了什么还是一个粗糙的边缘?

4

1 回答 1

1

如果您分两步编译,首先是 Type DictionarySingleton,然后是 Function memoize。看起来编译器首先尝试找出下划线的类型(可能是泛型类型),然后在确定它之前obj它还尝试推断 r 的类型。所以到那时它还没有与 统一obj,这就是如果你一次编译它会失败的原因。

于 2012-06-24T18:58:40.720 回答