Haskell: defining types which include classes

toughwimp11

Senior member
May 8, 2005
415
0
76
Is it possible to define types in Haskell which include as one of the fields an element which is a member of a certain class?

For example, say I want to define rational numbers as a tuple of two Nums, how would i do something along these lines:

type (Num a) => Q b = (a,a)

Currently that gives me an error but it seems as if something like this should be possible
 

dinkumthinkum

Senior member
Jul 3, 2008
203
0
0
You can type-class restrict a type variable in a data or newtype declaration, but not an ordinary type alias like you wrote. For example,

Code:
data Num a => MyType a = MyConstructor (a, a)

However, the other way to go about this is to leave the type declaration alone and just type-class restrict all of the functions that operate on it:

Code:
myFunction :: Num a => MyType a -> MyType a

Note that there is a rational number type already in the Data.Ratio module, and it is effectively defined like this:

Code:
data Ratio a = a % a
numerator :: (Integral a) => Ratio a -> a
denominator :: (Integral a) => Ratio a -> a

so that you can write ratios like this: 1%2.

(It is not actually defined quite like this because the (%) function needs to reduce the rational number to lowest form)
 
Last edited: