2

ダミーの例を次に示します。

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 が型変数を推測できないという事実から発生し、解決策はtypeclass の定義からb0パラメーターを削除することです。でも、現実には、できません。bTest

私の質問は次のとおりです。行で指定されたb0明示的なパラメーターで明示的に識別する方法はありますか?bf :: Test a b => a

ありがとう。

4

1 に答える 1

1

Joachim Breitner の提案を具体化すると、型シグネチャを引数 orwitnessに変更できる場合に使用できます。proxy b -> aConstant a b

2 つのアプローチはほとんど同等であるため、好みの問題です。

{-# 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 に答える