我有一个与Haskell类型系统有关的问题.这不是我第一次遇到类型系统的限制.我将省略我的项目详细信息并使用简化示例.这是一些代码:
-- Works
foo :: (Bounded a, Enum a) => a
foo = minBound
-- "ambiguous" constraint:
-- 'a' has no occurrences in type declaration
bar :: (Bounded a, Enum a) => Int
bar = fromEnum minBound
-- Too much information in return
-- but I can show haskell the appropriate type of 'min'
baz :: (Bounded a, Enum a) => (a, Int)
baz = let min = minBound
in (min, someFunction . fromEnum $ min)
-- Type constraint 'a' not ambiguous
-- (or at least that isn't the compiler error message)
-- but Haskell doesn't know which 'minBound' to use
barrer :: (Bounded a, Enum a) => a
barrer = let min = minBound -- <- min's type is ambiguous
in toEnum . someFunction . fromEnum $ min
Run Code Online (Sandbox Code Playgroud)
我想要实现的类似于barrer:首先,使用minBound特定于值的值a并将其"转换"为整数.在我的项目中,我继续转换这个整数(以避免在使用类型时出现中间算术溢出a)并将它们"转换"为类型a(经过一些mod魔法).我怎样才能告诉Haskell合适的类型minBound?可能吗?
显而易见的解决方案是添加注释minBound :: a.这也可以解决bar.问题:类型变量a好像出的在函数定义范围,因为注入新活力的Haskell minBound :: a到minBound a0错误消息.有没有办法做这种类型的注释?
我使用的一个糟糕的黑客是minBound通过将它包含在函数的返回类型中来约束调用的类型baz.这个解决方案并不理想.有没有人有一些建议?
Yuu*_*uri 14
该ScopedTypeVariables延伸正好解决您的问题.该页面还提供了一些替代解决方案(asTypeOf和undefined参数).