3 ms·
Haskell still has some boilerplate - actually quite a lot if you don't use -XGeneralizedNewtypeDeriving (which has known problems when used with other extension
by sparkie 13y ago
Haskell still has some boilerplate - actually quite a lot if you don't use -XGeneralizedNewtypeDeriving (which has known problems when used with other extensions). With newtype deriving, this is about as simple as it gets:
{-# 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.
- tel 13y agoGeneralizedNewtypeDeriving's problems are fixed in the newest GHC which just had it's first RC a few days ago. It introduces a "roles" system which tracks which types are allowed to use GND without breaking abstraction boundaries. Roles are mostly invisible to end users as well.