[Haskell-beginners] typeclass confusion
John Obbele
john.obbele at gmail.com
Tue Aug 24 06:16:39 EDT 2010
On Tue, Aug 24, 2010 at 05:06:05AM +0200, Tobias Brandt wrote:
> 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
I may look like a nitpicker but the above function definitions
lose their type information. I'd have written it this way:
data Angle a = Radians a | Degrees a deriving (Eq, Show)
rad :: Floating a => Angle a -> Angle a
rad (Radians x) = Radians x
rad (Degrees x) = Radians (pi * x / 180)
deg :: Floating a => Angle a -> Angle a
deg (Radians x) = Degrees (180 * x / pi)
deg (Degrees x) = Degrees x
On the other side, I am not particularly confident this approach
is the best. Other people may give you better solutions …
/‡ John
More information about the Beginners
mailing list