Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lists of data types: "could not deduce (a ~ SomeType) from the context (SomeTypeclass a)"

Tags:

types

haskell

I have the following problem with Haskell's type system: I am trying to declare a data type and return a list containing elements of this type from a function. Unfortunately, even a minimal testcase such as

data SampleType = SampleTypeConstructor

instance Show SampleType where
    show x = "(SampleType)"

stList :: (Show a) => [a]
stList = [(SampleTypeConstructor)]

main = do {
    putStrLn (show stList)
}

fails with the following error message from both ghc-7.0.2 and ghc-7.1.20110327:

tcase.hs:7:12:
    Could not deduce (a ~ SampleType)
    from the context (Show a)
      bound by the type signature for stList :: Show a => [a]
      at tcase.hs:7:1-34
      `a' is a rigid type variable bound by
          the type signature for stList :: Show a => [a] at tcase.hs:7:1
    In the expression: (SampleTypeConstructor)
    In the expression: [(SampleTypeConstructor)]
    In an equation for `stList': stList = [(SampleTypeConstructor)]
like image 896
RavuAlHemio Avatar asked Mar 28 '11 00:03

RavuAlHemio


1 Answers

the offending line is stList :: (Show a) => [a]. You're declaring that stList is a polymorphic list that holds any element which satisfies the show constraint. But stList isn't a polymorphic list! It's a list of SampleTypes. So remove the signature and see what ghci infers, or just give it the correct signature: :: [SampleType].

like image 143
sclv Avatar answered Oct 19 '22 06:10

sclv