4 ms·
This is a good trick but it needs to be used judiciously or you'll end up with lots of boilerplate. I particularly like Go's type system, though, because it ma
by skybrian 13y ago
This is a good trick but it needs to be used judiciously or you'll end up with lots of boilerplate.
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.
- hdevalence 13y agoOn the other hand, Go doesn't have a way to write code that abstracts over types, and my (albeit limited) experience with Go is that most of the boilerplate is due to the language's poor type system. If you use a language with a better type system (Haskell is the first that comes to mind, though there are others), you can actually do this sort of thing without the boilerplate code.
- sparkie 13y agoHaskell 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.
- herge 13y agoI got annoyed with Go when I learnt how hard it is to sort arbitrary lists. Doing the following in Go is quite a pain: scores = [{'name': 'Bob', 'score': 20}, {'name': 'Jane', 'score': 15}] scores.sort(key=lambda x: x['score'])
- skybrian 13y agoYes, there is in practice a fair bit of boilerplate in Go. (The way you'd do it in this case is by defining two new types for a struct and a slice of structs. Not that hard once you know the trick.) Still, they got tiny types right, and without getting bogged down in dimensional analysis.