[Haskell-cafe] Context for type parameters of type constructors
Dylan Thurston
dpt at lotus.bostoncoop.net
Tue Mar 30 00:31:46 EST 2004
On Mon, Mar 29, 2004 at 06:00:57PM +0200, Henning Thielemann wrote:
> Thus I setup a type constructor VectorSpace
> in the following way:
>
> > module VectorSpace
> > where
> >
> > class VectorSpace v where
> > zero :: v a
> > add :: v a -> v a -> v a
> > scale :: a -> v a -> v a
>
> I haven't added context requirements like (Num a)
> to the signatures of 'zero', 'add', 'scale'
> because I cannot catch all requirements
> that instances may need.
>
> The problematic part is the 'scale' operation
> because it needs both a scalar value and a vector.
> Without the 'scale' operation
> 'v' could be simply a type (*)
> rather than a type constructor (* -> *).
Right.
I recommend you use multi-parameter type classes, with a type of the
scalars and the type of the vectors. For the method you're using, you
need to add a 'Num a' context. You say that you 'cannot catch all
requirements that instances may need', but certainly any instance will
need that context.
If you use multi-parameter type classes, then in your instance
declaration you can specify exactly what requirements you need. For
instance:
> class VectorSpace v a where
> zero :: v
> add :: v -> v -> v
> scale :: a -> v -> v
> instance VectorSpace IntArray Int where ...
> instance (Num a) => VectorSpace (GenericArray a) a where ...
Peace,
Dylan
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20040330/3d0c1d30/attachment.bin
More information about the Haskell-Cafe
mailing list