Checking that two values have the same head constructor

haskell

Solution

If you're willing to derive `Data` then you're good to go.

{-# LANGUAGE DeriveDataTypeable #-}

import Data.Data

data E = A Int | B String | C deriving (Typeable, Data)

sameCons :: E -> E -> Bool
sameCons x y = toConstr x == toConstr y

ghci> sameCons (A 1) (A 3)
True
ghci> sameCons (A 1) (C)
False

Problem

I'd like to be able to write a function which checks that two values have been built using the same head constructor. This function: shouldn't be linear in the size of the datatype declaration should keep working if the datatype is extended e.g. this is not satisfactory (it is linear and the catchall will invalidate the function if I add any extra constructor): ``` data E = A Int | B String | C sameCons :: E -> E -> Bool sameCons t u = case (t, u) of (A{}, A{}) -> True (B{}, B{}) -> True (C{}, C{}) -> True _ -> False ``` In OCaml it is possible to use unsafe functions from the `Obj` module to do exactly that. Can we do something similar in Haskell (a ghc-specific solution works too)?

Original source

Related problems