by hdevalence · 12y ago · 0 comments
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
class Degrees deg where
toK :: deg -> K
fromK :: K -> deg
newtype K = K { unK :: Double } deriving (Show)
instance Degrees K where
toK = id
fromK = id
newtype C = C { unC :: Double } deriving (Show)
instance Degrees C where
toK = K . (+ 273.16) . unC
fromK = C . (flip (-) 273.16) . unK
newtype F = F { unF :: Double } deriving (Show)
instance Degrees F where
toK = K . (+ 273.16) . (* (5/9)) . (flip (-) 32) . unF
fromK = F . (+ 32) . (* (9/5)) . (flip (-) 273.16) . unK
Without newtype deriving (or other generic deriving extensions), one would need to implement instances of {Num, Real, Fractional, RealFrac, Floating, RealFloat} for all three types, which do nothing but map to the Double equivalents.