haskell - 错误 `Could not deduce (a ~ b)` 是什么意思?

标签 haskell types

我正在修改以下代码作为作业的一部分:

rand :: Random a => State StdGen a
rand = do
    gen <- get
    let (x, gen') = random gen
    put gen'
    return x

我被要求编写一个函数randR,它完成与rand 函数相同的任务,但允许指定一个范围。所需的类型是Random a => (a, a) -> State StdGen a。我编写了以下代码:

randR :: Random a => (a, a) -> State StdGen b
randR (lo, hi) = do
    gen <- get
    let (x, gen') = randomR (lo, hi) gen
    put gen'
    return x

这看起来是正确的;它几乎和模型一模一样。但我收到以下错误:

Could not deduce (a ~ b)
from the context (Random a)
  bound by the type signature for 
             randR :: Random a => (a, a) -> State StdGen b

(a ~ b) 是什么意思,为什么编译器不能从“上下文”中“推断”它?

最佳答案

错误消息表明 randR 的签名中存在拼写错误:randR::Random a => (a, a) -> State StdGen b。它应该是 ... -> RandState a

该消息粗略地指出,编译器知道 ab 需要是同一类型,但无法证明情况确实如此。 a ~ b"equality constraint" ;将 ~ 大致理解为 =

有关上下文的部分只是编译器告诉您它对类型约束的了解的方式。在这种情况下,它几乎完全没有帮助,但您经常会看到类似 Could not derduc (Floating a) from the context (Num a) 的内容或其他一些表明该函数需要额外约束的直接指示.

顺便说一句,通过一些扩展,您可以通过添加 GHC 要求的约束来解决此问题:randR::(Random a, a ~ b) => (a, a) -> State StdGen b 应该可以正常工作。 (我认为。)为了您的目的,不必担心这个......

关于haskell - 错误 `Could not deduce (a ~ b)` 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26919382/

相关文章:

algorithm - 表示连续概率分布

algorithm - 我可以将红黑树表示为二叉叶树吗?

python - 无法从 njit 函数内部调用 numba 函数

c++ - 隐式转换被认为是一个坏概念吗?

"foldl1 (\a b -> (and a + and b)) [(1,2), (3,4)] 的 Haskell 错误

haskell - 为什么 Identity monad 有用?

html - 使用 Lucid 进行简单示例

go - 如何获得带有反射的自定义类型?

haskell - Haskell 中的递归类型同义词 - 'cycle in type synonym declarations'

android - 有什么方法可以检查设备是否支持手写笔输入?