[Haskell-beginners] Could not deduce (Matrix m (Maybe a)) from the context (Matrix m a)

Daniel Fischer daniel.is.fischer at web.de
Fri Jan 29 05:31:33 EST 2010


Am Freitag 29 Januar 2010 10:45:32 schrieb Lyndon Maydwell:
> Thanks Daniel.
>
> It works, but I'm a bit confused as to why the extra type information is
> needed.

Well, you call fromRows on the result of vicinityRows.

vicinityRows m x y :: [[Maybe a]]

fromRows :: Matrix mat b => [[b]] -> mat b

So for 

fromRows (vicinityRows m x y)

to be well typed, you need an 

instance Matrix matr (Maybe a) where ...

for some matrix type matr. That has to come from somewhere. It might come 
from an

instance Matrix m a => Matrix m (Maybe a) where ...

or you can supply it as a constraint on the function vicinityMatrix.

However, having a look, none of the methods in the class look like they 
depend on the actual type a, so it might be better to have

class Matrix m where
    fromRows :: [[a]] -> m a
    toList :: m a -> [a]
    rows :: m a -> Integer
    columns :: m a -> Integer
    row :: m a -> Integer -> [a]
    column :: m a -> Integer -> [a]
    at :: m a -> Integer -> Integer -> a
    (!!!) :: m a -> Integer -> Integer -> a
    vicinityRows :: m a -> Integer -> Integer -> [[Maybe a]]
    vicinityMatrix :: m a -> Integer -> Integer -> m (Maybe a)
    -- No constraint needed!!
    neighbours :: m a -> Integer -> Integer -> [a]

>
> On Fri, Jan 29, 2010 at 5:17 PM, Daniel Fischer
>
> <daniel.is.fischer at web.de> wrote:
> >
> > Well, the error says the compiler (the type checker) can't deduce the
> > context (Matrix m (Maybe a)) from the givens. If you supply that
> > information,
> >
> > vicinityMatrix :: Matrix m (Maybe a) =>
> >               m a -> Integer -> Integer -> m (Maybe a)
> >
> > it'll work.
> >
> >> Thanks guys.
> >>
> >> ---
> >>
> >> My Matrix class definition follows below:
> >>
> >> module Matrix (Matrix) where
> >>
> >> import Data.Array
> >> import Data.Maybe (catMaybes)
> >> import Control.Monad (guard)
> >>
> >> class Matrix m a
> >>   where
> >>     fromRows       :: [[a]] -> m a
<snip>
> >>     vicinityRows   :: m a   -> Integer -> Integer -> [[Maybe a]]
> >>     vicinityMatrix :: m a   -> Integer -> Integer -> m (Maybe a)


More information about the Beginners mailing list