【发布时间】:2012-10-24 18:08:23
【问题描述】:
我有一个用于数学向量的自定义类型类
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
class Vector v a where
infixl 6 <+>
(<+>) :: v -> v -> v -- vector addition
infixl 6 <->
(<->) :: v -> v -> v -- vector subtraction
infixl 7 *>
(*>) :: a -> v -> v -- multiplication by a scalar
dot :: v -> v -> a -- inner product
我想将数字a 和函数a -> vector 放入该类的实例中。数字很简单:
instance Num a => Vector a a where
(<+>) = (+)
(<->) = (-)
(*>) = (*)
dot = (*)
我认为函数也很简单(好吧,除了dot,但我可以忍受)
instance Vector b c => Vector (a -> b) c where
f <+> g = \a -> f a <+> g a
f <-> g = \a -> f a <-> g a
c *> f = \a -> c *> f a
dot = undefined
但是,我收到以下错误:
Ambiguous type variable `a0' in the constraint:
(Vector b a0) arising from a use of `<+>'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: f a <+> g a
In the expression: \ a -> f a <+> g a
In an equation for `<+>': f <+> g = \ a -> f a <+> g a
我如何告诉 GHC 该实例对 所有 类型 a 有效?我应该在哪里添加类型签名?
【问题讨论】:
-
这种方式可能是不可能的,毕竟
Vector b c与不同c的所有实例可能具有<+>的不同行为,即使c实际上并没有出现在签名中的那个功能。 ——你是故意避开fundeps(或type family)还是单独开一个additiveGroup类? vectorspace 确实做到了两者,这肯定是有原因的。 -
不,我不是故意避开它们。制作一个加法组类当然看起来很明智。我会调查基金并报告。