以下 Haskell 代码无法编译:
getMaxBound :: (Bounded a) => a -> a
getMaxBound _ = maxBound :: a
我得到的错误如下:
Could not deduce (Bounded a1) arising from a use of ‘maxBound’
from the context: Bounded a
bound by the type signature for:
getMaxBound :: Bounded a => a -> a
at rot13.hs:3:1-36
为什么我不能在 Haskell 中获取有界类型的 maxBound?
理想情况下,我会像这样使用这个函数:
getMaxBound 3
> 9223372036854775807
getMaxBound 'c'
> '\1114111'
我觉得每次我有任何类型 a
有一个 Bounded 实例时,我应该能够获得该类型的 maxBound。
我错过了什么?
最佳答案
Willem 的回答在这种情况下应该工作得很好,但在更复杂的情况下也可能有用的替代方法是使用 -XScopedTypeVariables
如果您将 {-# LANGUAGE ScopedTypeVariables #-}
行添加到文件顶部,您的代码应该可以编译。
扩展的作用是允许您在内部作用域中引用外部作用域的类型变量。在你的代码中,a
被隐藏在函数体中,它与外部 a
之间没有任何联系,导致你丢失了 Bounded a
上下文!
关于haskell - 如何获取具有 Bounded 实例的类型的 maxBound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54266529/