8

我有一个用于数学向量的自定义类型类

{-# 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?我应该在哪里添加类型签名?

4

2 回答 2

6

类型族绝对是解决这个问题的最好方法

{-# LANGUAGE TypeFamilies, FlexibleContexts #-} 
class VectorSpace v where
    type Field v

    infixl 6 <+>
    (<+>) :: v -> v -> v  -- vector addition

    infixl 6 <->
    (<->) :: v -> v -> v  -- vector subtraction

    infixl 7 *>
    (*>)  :: Field v -> v -> v  -- multiplication by a scalar

    dot   :: v -> v -> Field v  -- inner product

从数学上讲,要使用函数创建向量空间,您必须重用相同的字段:

instance VectorSpace b => VectorSpace (a -> b) where
    type Field (a -> b) = Field b
    f <+> g = \a -> f a <+> g a
    f <-> g = \a -> f a <-> g a
    c *>  f = \a -> c *> f a
    dot     = error "Can't define the dot product on functions, sorry."

...关于类型族的好处是它们的工作方式与您解释的方式非常相似。让我们做两个向量空间的直接乘积:

instance (VectorSpace v,VectorSpace w, Field v ~ Field w,Num (Field v)) => VectorSpace (v,w) where
    type Field (v,w) = Field v
    (v,w) <+> (v',w') = (v <+> v',w <+> w')
    (v,w) <-> (v',w') = (v <-> v',w <-> w')
    c *> (v,w) = (c *> v, c*> w)
    (v,w) `dot` (v',w') = (v `dot` v') + (w `dot` w')

Num您可以用自定义代数类替换上下文,但Num可以很好地捕捉字段的概念。

于 2012-10-23T17:13:19.347 回答
2

我能够编译下面的小例子(在 Conal Elliott 的向量空间包之后设计):

{-# LANGUAGE TypeFamilies #-}

module Main
       where

class Vector v where
  type Scalar v

  infixl 6 <+>
  (<+>) :: v -> v -> v  -- vector addition

  infixl 7 *>
  (*>)  :: (Scalar v) -> v -> v  -- multiplication by a scalar

instance Vector v => Vector (a -> v) where
  type Scalar (a -> v) = (a -> Scalar v)
  f <+> g = \a -> f a <+> g a
  (*>) c f  = \a -> c a *> f a -- Can't deduce that Scalar v ~ Scalar (a -> v)

可以使用功能依赖项而不是类型族来使其工作。

于 2012-10-23T12:35:26.740 回答