xiaolingxiao
xiaolingxiao

Reputation: 4895

How do you make a functor instance of Matrix and Vector from hmatrix library?

Both Matrix and Vector constructor has kind *->*, so they look like value constructors. But when I try something like

instance Functor Vector a where
    fmap g ( Vector a ) = Vector ( g a )

I get this error:

 Not in scope: data constructor `Vector'

which makes sense since I can't make a vector by using let v = Vector [1..3] anyways. But checking the source I see that both Matrix and Vector constructor are exported from their respective modules:

Vector.hs
module Data.Packed.Vector (
    Vector,
    fromList, (|>), toList, buildVecto.. 
) where

Matrix.hs

module Data.Packed.Matrix (
    Element,
    Matrix,rows,cols...
) where

Dido for applicative functor, monad, etc.

Upvotes: 3

Views: 680

Answers (2)

Cubic
Cubic

Reputation: 15673

module Data.Packed.Vector (
    Vector,
    fromList, (|>), toList, buildVecto.. 
) where

This exposes the type Vector, but not any of it's constructors.

Your instance declaration corrected:

instance Functor Vector where
    fmap  = V.map

(assuming you import Vector as V, and further assuming you're talking about the Vector from the vector package).


EDIT: Sorry, didn't see you mentioned the package name. For hmatrix Vectors, it would be mapVector instead of V.map.

EDIT_ 2: As mentioned by the others, for hmatrix this won't work because Matrix and Vector require Storeable for their content.

Upvotes: 2

Alberto Ruiz
Alberto Ruiz

Reputation: 411

As Conrad Parker said, we need Storable instances.

Using recent ghc extensions we can define a more general Functor':

{-# LANGUAGE ConstraintKinds, TypeFamilies #-}

import Numeric.LinearAlgebra
import Foreign.Storable(Storable)
import GHC.Exts (Constraint)

class Functor' c where
  type Ok c u v :: Constraint
  type Ok c u v = ()

  fmap' :: Ok c u v => (u -> v) -> c u -> c v

instance Functor' Vector where
  type Ok Vector u v = (Storable u, Storable v)
  fmap' = mapVector

Upvotes: 6

Related Questions