25c35e90595b236da0fee29edb70db7f

For two given data types, Simple and Complex, define a function which returns whether the variable is of type Complex.
A student asked this on a forum some time ago, and the only solution I could come up with is this. It works, but I wonder: is there another way to do it? is there a _better_ way to do it? is there a possible practical significance or is the task totally contrived?

Example of usage (in GHCi):

*Main> is_complex (Struct "one" [("two", Mystring "three"), ("four", Mystring "five")])
True
*Main> is_complex (Myint 3)
False

class IsComplex a where
    isComplex :: a -> Bool

data Simple = Myint Int | Mydouble Double | Mystring String deriving (Eq, Show)
data Complex = Struct String [(String,Simple)] deriving (Eq, Show)

instance IsComplex Simple where
    isComplex  _ = False

instance IsComplex Complex where
    isComplex _ = True


is_complex :: IsComplex a => a -> Bool
is_complex a = isComplex a

Refactorings

No refactoring yet !

25c35e90595b236da0fee29edb70db7f

headcrab.myopenid.com

December 8, 2009, December 08, 2009 22:19, permalink

No rating. Login to rate!

Have written this variation. Usage:
*Main> is_complex (UserSimple $ Myint 1)
False
*Main> is_complex (UserComplex $ Struct "one" [("two", Myint 3)])
True

data Simple = Myint Int | Mydouble Double | Mystring String deriving (Eq, Show)
data Complex = Struct String [(String,Simple)] deriving (Eq, Show)

data UserType = UserSimple Simple | UserComplex Complex

is_complex :: UserType -> Bool
is_complex (UserSimple a) = False
is_complex (UserComplex a) = True
F6cb924dfb4488d701934a5485f5fa24

liamoc

December 26, 2009, December 26, 2009 14:47, permalink

No rating. Login to rate!
-- Your second example is completely contrived, seeing as the user has to annotate a type anyway, you could just write:
is_complex_simple = False
is_complex_complex = True

-- As for answering your question, there is in fact no easy way to select based on types other than type-class predicate dictionaries (as you have done) as all other type information vanishes at compile time. This isn't really a common usage though for type-classes.

Your refactoring





Format Copy from initial code

or Cancel