我有这个代码:
{-# LANGUAGE MultiParamTypeClasses #-}
import System.Random (RandomGen(..))
class RandomGen gen => Shadow gen light where
shadowRay :: gen -> light -> Float
eval :: light -> Float
我得到那个错误:
[1 of 1] Compiling Main ( problem.hs, problem.o ) problem.hs:6:5: error: * Could not deduce (Shadow gen0 light) from the context: Shadow gen light bound by the type signature for: eval :: Shadow gen light => light -> float -> float at problem.hs:6:5-40 The type variable `gen0' is ambiguous * In the ambiguity check for `eval' To defer the ambiguity check to use sites, enable AllowAmbiguousTypes When checking the class method: eval :: forall gen light. Shadow gen light => forall float. light -> float -> float In the class declaration for `Shadow'
这是GHC 7.10+的问题。在它工作之前。如果我将"gen"参数添加到"eval",则有一个修复方法,例如:
eval :: gen -> light -> Float
但我不想添加一个不会被使用的新值参数。有没有其他方法进行类型解析?
问题是eval
不使用gen
,因此在选择要使用的Shadow
实例时,专门化其类型不足以决定使用哪个gen
。一种可能的解决方案是使用功能依赖关系来强制每个light
选择只有一个gen
:
{-# LANGUAGE FunctionalDependencies #-}
class RandomGen gen => Shadow gen light | light -> gen where
shadowRay :: gen -> light -> Float
eval :: light -> Float
但是,您可能不希望或不需要以这种方式耦合light
和gen
。在这种情况下,您可能需要考虑从类型类中删除gen
的相反替代方法 - 如果gen
和light
不相关,则不需要多参数类型类来关联它们:
class Shadow light where
shadowRay :: RandomGen gen => gen -> light -> Float
eval :: light -> Float