Canonical way to test data types

Viewed 69
import Data.Typeable(typeOf)

myFunc :: (Show a) => [a] -> [String]
myFunc
  | show (typeOf a) == "[Char]" = ...
  | otherwise = .. 

I use the above code to test if the input is of the String type. Is this correct and acceptable or are there other better ways?

1 Answers

Like with matching values, we prefer to avoid using booleans altogether. In context of typeable/dynamic, this means you shouldn't “test” whether it is some particular type and then do something if it is, but instead (like with value pattern-matching) you simply try to use it as that type, and then add fallback cases just for when that fails.

myFunc' :: (Show a, Typeable a) => a -> String
myFunc' x = case cast x of
       Just xStr -> xStr
       _ -> show x

Note that I don't even need to mention that xStr handles the case where x is String, because that is already implied by the context.

Related