无法推断 (TypeClass a0) 因使用“变量”而产生

Could not deduce (TypeClass a0) arising from a use of ‘variable’

我有一个类型:

type DifferentiableFunction n a = (Function n a, List n (Function n a), String)

我在其他地方定义:

data Something where
  Operator :: Something -> (forall a . Floating a => DifferentiableFunction n a) -> Something

现在我尝试模式匹配:

case something of
  (Operator s f) -> let (_, _, l) = f in l

我得到 Could not deduce (Floating a0) arising from a use of ‘f’。我不明白为什么会这样。

问题是 let (_, _. l) = f in l 没有指定 f 使用什么类型:它可能是 DifferentiableFunction n DoubleDifferentiableFunction n Float 或其他类型。因为你只使用了不依赖于 a 的部分(l 只是一个 String,不管 a 是什么),编译器无法决定什么类型f 应该有(a 是模棱两可的,即编译不知道为 a 选择什么)。

因此,解决方案是为 f:

提供显式类型签名
case something of
  (Operator s f) -> let (_, _, l) = (f :: DifferentiableFunction n Double) in l

或者,将 String 从 forall 中取出:

type DifferentiableFunction n a = (Function n a, List n (Function n a))
data Something where
  Operator :: Something -> (forall a . Floating a => DifferentiableFunction n a) -> String -> Something -- String is not inside the `forall a.`

现在您无需选择特定的 a 即可获得 String,因为它确实独立于 a