• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Haskell: defining types which include classes

toughwimp11

Senior member
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
 
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:
Back
Top