Search code examples
haskellderiving

When should we put parenthesis after deriving?


I see two expressions

data BinTree a = BTNil | BTNode a (BinTree a) (BinTree a) deriving Show

data Day = Sunday | Monday | Tuesday | Wednesday
         | Thursday | Friday | Saturday         deriving (Enum)

I am confusing when I should use parenthesis after deriving. I know we should use parenthesis and commas where there are more than one classes.


Solution

  • In every sensible use case, there's no distinction between the two.

    ... deriving (A)
    ... deriving  A
    

    are perfectly equivalent. As you've already correctly pointed out, the parentheses are necessary if you have multiple classes to derive from. Personally, I always include the parentheses, simply for the sake of consistency. But it's entirely a style choice, and as long as you're consistent, it doesn't really matter.


    For the sake of absolute completeness, there is technically one case where it's necessary. If for some reason you have a typeclass which is an operator name, you will need to supply the parentheses to make it work.

    {-# LANGUAGE TypeOperators, MultiParamTypeClasses,
        GeneralizedNewtypeDeriving #-}
    
    class (:+) a
    
    -- newtype Foo a = Foo a deriving   :+   -- Definitely a syntax error
    -- newtype Foo a = Foo a deriving  (:+)  -- Confuses the parser (error)
    newtype Foo a    = Foo a deriving ((:+)) -- Works