多态“常量”,例如5 :: Num a => a
,并不是真正的常量,而是字典参数的函数。因此,如果您定义
primes :: Num n => [n]
primes = ...
Bad example of course, there's no good reason here to have it polymorphic... what I'm really interested is if you try to globally memoise a nontrivial polymorphic function, with e.g. memo-trie
s.
then this sequence won't be shared between calls from different sites, which isn't nice in terms of performance. (Isn't this the main reason the Haskell standard blessed us with the Dreaded Monomorphism Restriction?)
我能看到如何强制共享的唯一方法是为约束类的每个实例提供一个单态“标签”。例如。
erastothenes :: Num n => [n]
erastothenes = ...
class (Num n) => HasPrimes n where
-- | @'primes' ≡ 'erastothenes'@
primes :: [n]
integerPrimes :: [Integer]
integerPrimes = erastothenes
instance HasPrimes Integer where
primes = integerPrimes
...这在优雅方面不太好。
有没有更好的方法来实现这样的记忆?
由于技术原因,这是相当不可能的。类型类是开放的,因此,多态常量在编译时不一定“看到”有多少类型满足约束,因此它无法分配那么多单态 thunk。另一方面,类型类当然无法看到它可能生成的所有可能的常量,因此不能在类型类字典中分配单态 thunk。
您必须明确提及您想要分配单态 thunk 的任何类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)