使函数成为矢量类型类的实例

Chr*_*lor 8 haskell types typeclass

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

{-# 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
Run Code Online (Sandbox Code Playgroud)

我想将数字a和函数a -> vector放入类的实例中.数字很​​简单:

instance Num a => Vector a a where
    (<+>) = (+)
    (<->) = (-)
    (*>)  = (*)
    dot   = (*)
Run Code Online (Sandbox Code Playgroud)

而且我认为功能也很简单(好吧,除了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
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

如何告诉GHC该实例对所有类型都有效a?我应该在哪里添加类型签名?

And*_*ewC 5

类型系列绝对是解决这个问题最可靠的方法

{-# 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
Run Code Online (Sandbox Code Playgroud)

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

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."
Run Code Online (Sandbox Code Playgroud)

......关于类型系列的好处是它们非常适合你解释的方式.让我们做两个向量空间的直接乘积:

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')
Run Code Online (Sandbox Code Playgroud)

您可以Num使用自定义代数类替换上下文,但Num可以很好地捕获Field的概念.