2

这是一个虚拟示例:

class Test a b where
  witness :: a

f :: Test a b => a
f = witness

哈斯克尔然后说

Could not deduce (Test a b0) arising from a use of ‘witness’
from the context (Test a b)
  bound by the type signature for f :: Test a b => a
  at test.hs:8:6-18
The type variable ‘b0’ is ambiguous
Relevant bindings include f :: a (bound at test.hs:9:1)
In the expression: witness
In an equation for ‘f’: f = witness

错误来自 Haskell 无法推断类型变量的事实,解决方案是从 typeclass 的定义中b0删除参数。但是,实际上,我做不到。bTest

我的问题是:是否存在一种明确识别行中给出的b0显式参数的方法?bf :: Test a b => a

谢谢。

4

1 回答 1

1

充实Joachim Breitner 的建议witness如果您可以将其类型签名更改为proxy b -> a参数或Constant a b.

这两种方法大多是等价的,所以这是一个偏好问题:

{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
module SO33958506 where

import Data.Functor.Constant
import Data.Proxy

class Test a b where
  constantWitness :: Constant a b
  proxyWitness :: proxy b -> a

constantWitnessWithProxy :: forall proxy a b. Test a b => proxy b -> a
constantWitnessWithProxy _ = getConstant $ (constantWitness :: Constant a b)

proxyWitnessAsConstant :: forall a b. Test a b => Constant a b
proxyWitnessAsConstant = Constant $ proxyWitness (Proxy :: Proxy b)
于 2015-11-27T14:20:40.053 回答