Search code examples
haskelltuplestemplate-haskell

What is the Unit type?


Normally in Haskell, tuples of length one aren't allowed (AFAIK). However, when messing with Template Haskell, I got this:

oneElementTuple = $(do{
    x <- newName "x";
    return $ LamE
        [VarP x]
        (TupE [Just (VarE x)]) -- one element tuple?
})

GHCi tells me that oneElementTuple is of type a -> Unit a. I couldn't find any documentation on this Unit type, and it doesn't seem to be an instance of any basic typeclasses like Show or Functor. So, where is Unit defined, if it isn't just built-in magic? Is it at all useful?


Solution

  • There's a Unit type defined in GHC.Tuple.

    Quoting the source:

    -- The desugarer uses 1-tuples,
    -- but "()" is already used up for 0-tuples
    -- See Note [One-tuples] in TysWiredIn
    data Unit a = Unit a
    

    Nothing fancy. It has no special tuple syntax. It looks like TH uses this type when one tries to make a one-tuple as you did.

    Note that since this type in inside a GHC. module, it is considered low-level. Normally, when needing one-tuples in everyday programming, one uses the Identity newtype instead (which also avoids the additional lifting of Unit).