ishak lahlouh
ishak lahlouh

Reputation: 65

error: Not in scope: type variable [Haskell]

i want a list of numerical values in my data type

data Polynomial = Polynomial {xs ::(Num a) => [a] } deriving (Show)

but i'm still getting this Error

error: Not in scope: type variable ‘a’

Upvotes: 3

Views: 3103

Answers (2)

Brandon Chinn
Brandon Chinn

Reputation: 141

If you have access to the ExistentialQuantification language extension, you can do this:

data Polynomial = forall a. Num a => Polynomial { xs :: [a] }

You can also derive Show with StandaloneDeriving:

data Polynomial = forall a. (Show a, Num a) => Polynomial { xs :: [a] }
deriving instance Show Polynomial

Upvotes: 1

Code-Apprentice
Code-Apprentice

Reputation: 83517

According to the Haskell wiki

In Haskell 98, only functions can have type constraints.

In order to do what you want, you can declare Polynomial with a type parameter. Then you write functions with the appropriate type constraints.

data Polynomial a = Polynomial xs
    deriving (Show)

This allows you to construct concrete polynomial types such as Polynomial Int or Polynomial Float or even Polynomial String. A function which operates on your Polynomial type can declare constraints on the type parameter. For example a function to add two polynomials can have the following signature:

(+) :: (Num a) => Polynomial a -> Polynomial a -> Polynomial a

Rinse and repeat as appropriate for each function.

Upvotes: 8

Related Questions