[Haskell-beginners] typeclass confusion

Tobias Brandt tob.brandt at googlemail.com
Mon Aug 23 23:06:05 EDT 2010


You don't need a type class, you can just define your functions with pattern
matching:

rad :: Angle a -> a
rad (Radians x) = x
rad (Degrees x) = pi * (deg x) / 180

deg :: Angle a -> a
deg (Radians x) = 180 * (rad x) / pi
deg (Degrees x) = x

Alternatively, you can define Radians and Degrees as separate types and use
a type class:

data Radians a = Radians a
data Degrees a = Degrees a

class Angular a where
    rad :: a b -> b
    deg :: a b -> b

instance Angular Radians where
    rad (Radians x) = x
    deg (Radians x) = 180 * (rad x) / pi

instance Angular Degrees where
    rad (Degrees x) = pi * (deg x) / 180
    deg (Degrees x) = x

This would be extensible, but it this case not really useful.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100823/e24a6c00/attachment.html


More information about the Beginners mailing list