“无法推断(a〜b)”的错误是什么意思? [英] What does the error `Could not deduce (a ~ b)` mean?

查看:85
本文介绍了“无法推断(a〜b)”的错误是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我被要求写一个函数 randR 来完成相同的操作任务作为 rand 函数,但允许指定范围。所需的类型是 Random a => (a,a) - >状态标准a 。我写了下面的代码:

  randR :: Random a => (a,a) - >状态标准b 
randR(lo,hi)= do
gen < - get
let(x,gen')= randomR(lo,hi)gen
put gen'
return x

这看起来正确;它几乎完全像模型。但是我得到了以下错误:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'
由类型签名绑定
randR :: Random a => (a,a) - > State StdGen b

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

解决方案

randR 签名中存在拼写错误: randR :: Random a => (a,a) - >州标准b 。它应该是 ... - > RandState a



该消息大致表明,编译器知道 a b 需要是相同的类型,但它不能证明是这种情况。 a〜b 平等约束;阅读,大致意思是 =



关于上下文只是编译器告诉你它对于类型约束知道些什么的方法。在这种情况下,它几乎完全没有帮助,但通常你会看到像之类的东西无法从上下文(数字a)推断(浮动a)或其他一些直接指示该函数需要额外的约束。



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

I am modifying the following code as part of an assignment:

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

I was asked to write a function randR that accomplishes the same task as the rand function but allows for a range to be specified. The desired type is Random a => (a, a) -> State StdGen a. I wrote the following code:

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

This looks correct; it's almost exactly like the model. But I get the following error:

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

What does (a ~ b) mean, and why can't the compiler "deduce" it from the "context"?

解决方案

The error message indicates that there's a typo in the signature for randR: randR :: Random a => (a, a) -> State StdGen b. It should be ... -> RandState a.

The message roughly states that the compiler knows that a and b need to be the same type but that it can't prove that to be the case. a ~ b is an "equality constraint"; read ~ as roughly meaning =.

The part about the context is simply the compiler's way of telling you what it does know about the type constraints. In this case, it's almost completely unhelpful, but frequently you'll see something like Could not deduce (Floating a) from the context (Num a) or some other straightforward indication that the function needs an additional constraint.

Incidentally, with some extensions you could fix this problem by adding the constraint GHC asks for: randR :: (Random a, a ~ b) => (a, a) -> State StdGen b should work fine. (I think.) For your purposes, don't worry about this...

这篇关于“无法推断(a〜b)”的错误是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆