"Pattern matching" of algebraic type data constructors
Posted
by jetxee
on Stack Overflow
See other posts from Stack Overflow
or by jetxee
Published on 2010-04-13T08:39:26Z
Indexed on
2010/04/13
8:43 UTC
Read the original article
Hit count: 363
Let's consider a data type with many constructors:
data T = Alpha Int | Beta Int | Gamma Int Int | Delta Int
I want to write a function to check if two values are produced with the same constructor:
sameK (Alpha _) (Alpha _) = True
sameK (Beta _) (Beta _) = True
sameK (Gamma _ _) (Gamma _ _) = True
sameK _ _ = False
Maintaining sameK
is not much fun, it is potentially buggy. For example, when new constructors are added to T
, it's easy to forget to update sameK
. I omitted one line to give an example:
-- it’s easy to forget:
-- sameK (Delta _) (Delta _) = True
The question is how to avoid boilerplate in sameK
? Or how to make sure it checks for all T
constructors?
The workaround I found is to use separate data types for each of the constructors, deriving Data.Typeable
, and declaring a common type class, but I don't like this solution, because it is much less readable and otherwise just a simple algebraic type works for me:
{-# LANGUAGE DeriveDataTypeable #-}
import Data.Typeable
class Tlike t where
value :: t -> t
value = id
data Alpha = Alpha Int deriving Typeable
data Beta = Beta Int deriving Typeable
data Gamma = Gamma Int Int deriving Typeable
data Delta = Delta Int deriving Typeable
instance Tlike Alpha
instance Tlike Beta
instance Tlike Gamma
instance Tlike Delta
sameK :: (Tlike t, Typeable t, Tlike t', Typeable t') => t -> t' -> Bool
sameK a b = typeOf a == typeOf b
© Stack Overflow or respective owner