
I'd like to define an abstract type T, and some how make the following work:
3 :: T -- allow integer literals to be read as values of type T
100 :: T error: value out of bounds for type T -- place some restrictions on which integers are valid T values
To get the first feature, is my only option to make T an instance of the Num class? If so, I'd have to make fromIntegral return error for out of bounds values. Is there any problem in doing that? The only law I find mentioned for instances of Num is: abs x * signum x == x. Is this the complete requirement?

Hello Ashish Yes - to get integer literals for a type, you have to make that type an instance of Num. Making fromIntegral throw an out-of-bounds error is as much a problem as using error anywhere in your program. You get into the usual trade-off between robustness (handling errors, never dying) and clarity - often robustness isn't the primary virtue. If you wanted, you could use coercion in the fromIntegral implementation - say values over 100 are truncated to 100 rather than throw an error. Ideally a Num type should support the usual properties of addition, multiplication etc. (associative, commutative, identity for mult, ...) there is no enforcement of this though, and there are some strange Num instances "in the wild". Best wishes Stephen
participants (2)
-
Ashish Agarwal
-
Stephen Tetley