Haskell – simple constructor comparison (?) function

Take a look at Data.Data and its toConstr function. This returns a representation of the constructor which can be compared for equality.

With an extension (you can put {-# LANGUAGE DeriveDataTypeable #-} at the top of your module), you can have a Data instance derived for you automatically:

data PhpValue = VoidValue | IntValue Integer | BoolValue Bool 
              deriving (Typeable, Data)

You should then be able to use the toConstr function to compare by constructor.

Now the following will be true:

toConstr (BoolValue True) == toConstr (BoolValue False)

Using on from Data.Function you can now rewrite sameConstructor to:

sameConstructor = (==) `on` toConstr

This is the same as

sameConstructor l r = toConstr l == toConstr r

I think the version using on is easier to read at a glance.

Leave a Comment