[Haskell-beginners] typeclass confusion
ml at isaac.cedarswampstudios.org
Tue Aug 24 01:01:38 EDT 2010
On 08/23/10 22:33, Greg wrote:
> ...it would be nice to force
> the type system to check whether I'm using degrees or radians:
> data Angle a = Radians a
> | Degrees a
> deriving (Eq, Show)
You did it wrong... the difference between Radians and Degrees here is
only visible at runtime, as they are both of the same type, Angle.
Don't feel bad, this confused me for a while as a Haskell-beginner too.
An example to "force the type system to check" would be
data Radians a = Radians a deriving (Eq, Show)
data Degrees a = Degrees a deriving (Eq, Show)
Then you could make conversion functions, say,
radToDeg :: (Floating a) => Radians a -> Degrees a
degToRad :: (Floating a) => Degrees a -> Radians a
and implement them;
you *could* have a 'class Angle' or such, if you wanted... perhaps trig
functions or such would be sensible to put in there. And/or you could
try to make each data-type be a member of Num and related classes (being
able to add angles, etc)
For a real program, I think I would try to stick to just one unit (e.g.
radians) for internal program use (and convert any outside data to that
unit promptly), unless there was a reason that didn't work very well;
but the typeclass-stuff is an excellent thing to play with!
More information about the Beginners