by skybrian · 12y ago · 0 comments
I particularly like Go's type system, though, because it makes it very simple:
type celsius float64
There's no overhead and it doesn't attempt to prevent you from doing any calculations as a float64; the type checking just prevents direct assignments from a celsius type to another type. {-# 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.scores = [{'name': 'Bob', 'score': 20}, {'name': 'Jane', 'score': 15}] scores.sort(key=lambda x: x['score'])
Still, they got tiny types right, and without getting bogged down in dimensional analysis.