Is there a way to define multiple type synonyms in a single line?

My code is currently like this:

type Speed = Float
type Height = Float
type FuelMass = Float
type Gravity = Float

is there a way to not be wasting so much space by grouping the declarations, like

type (Speed, Height, FuelMass, Gravity) = Float

Upvotes: 1

Views: 132

Answers (2)

leftaroundabout
leftaroundabout

Reputation: 120711

Well, you can of course have any code generated for you by Template Haskell.

module MultiDefinitions where

import Language.Haskell.TH
import Control.Monad

multipleTypeSynonyms :: [Q Name] -> Q Type -> DecsQ
multipleTypeSynonyms synGs tG = do
  t <- tG
  forM synGs $ \synG -> do
    syn <- synG
    return $ TySynD syn [] t

Then

{-# LANGUAGE TemplateHaskell #-}

import Language.Haskell.TH
import MultiDefinitions

multipleTypeSynonyms
    (newName <$> ["Speed", "Height", "FuelMass", "Gravity"]) [t| Float |]

will generate the same definitions you wrote manually.

Is it a good idea to du stuff like that with TH? Hardly. In fact it is also not clear that type synonyms like that are a good thing at all – many Haskellers would argue that you should either use newtypes that actually give additional type safety (or use existing library types, such as from the units library), or else simply hard-code Float.

BTW there's seldom a good reason to use Float, just use Double.

Upvotes: 2

amalloy
amalloy

Reputation: 91857

No. A type definition is its own statement. If you really wanted to, you could group them on the same line by separating with semicolons instead of newlines, but this would be a very very unusual style.

Upvotes: 4

Related Questions