繁体   English   中英

指定来自 Haskell 术语的上下文

[英]Specify context from where comes term in Haskell

这是一个虚拟示例:

class Test a b where
  witness :: a

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

Haskell 然后说

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 无法推断类型变量b0的事实,解决方案是从类型类Test定义中删除参数b 但是,实际上,我不能。

我的问题是:是否存在一种方法可以使用f :: Test ab => a b给出的显式参数b显式识别b0

谢谢。

充实Joachim Breitner 的建议,如果您可以将其类型签名更改为proxy b -> a argument 或Constant ab ,则可以使用witness

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

{-# 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM